我在 MySQL 数据库中有客户表。我在 excel csv 中有客户列表,我想将 excel 数据导入 MySQL 客户表。我希望有人逐步向我展示如何做到这一点,并告诉模型 View 和 Controller 。
我已经编写了客户表的 MySQL 查询,以向您展示我将在 excel csv 中使用相同的列。
(`CustomerID`, `FirstName`, `LastName`, `JobTitle`, `BusinessPhone`, `MobilePhone`, `FaxNumber`, `Address`, `Area`, `State`, `ZipCode`, `Country`, `Email`, `Webpage`, `Notes`, `CustomerInvoice`, `Status`)
你想告诉我如何将csv数据导入MySQL表或者Yii有任何插件可以将excel数据导入MySQL数据库吗?
最佳答案
如果我理解正确,你可以在 Controller 操作中做一些事情
public function actionYourActionName(){
if (isset($_FILES['csv_file']) && !empty($_FILES['csv_file'])) {
$csv = array();
$file = fopen($_FILES['csv_file']['tmp_name'], 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
$csv[] = $line;
}
fclose($file);
for ($i = 1; $i < count($csv); $i++) {
$model = new YourmodelName();
foreach ($csv[0] as $key => $value) {
$model->$value = $csv[$i][$key];
}
if($model->save()){
//do here what you want to do after saving model
}else{return $model->getErrors();}
}
}
}else{
$this->render('your view name');
}
在您的 View 文件中,例如
echo CHtml::form('', 'post', array('id' => "verticalForm", 'class' => 'well form-vertical', 'enctype' => 'multipart/form-data'));
echo CHtml::fileField('csv_file[]', '', array('id' => 'csv_file', 'multiple' => 'multiple'));
echo '<p class="help-block">Please upload .csv files only.</p>';
echo CHtml::submitButton('Submit', array('class' => 'btn btn-primary'));
echo CHtml::endForm();
我想你已经为你的mysql表创建了一个模型,希望这对你有帮助
关于php - 如何在 yii 1.16 中将 excel 数据导入 mySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35595257/