1、fgetcsv导入 csv文件
public function actionFgetcsv(){
$startTime = microtime(true);
set_time_limit(0);
error_reporting(E_ALL & ~E_NOTICE);
ini_set('memory_limit','3072M');
$inputFileName = 'logapi/read/sku1.csv';
$row = 1;
$colKeyArr = ['sku','product_status','quantity_way','quantity_available'];
$rowDatas = [];
if (($handle = fopen($inputFileName, "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
$num = count($data);
#做处理,根据实际情况处理
for ($c=0; $c < $num; $c++) {
$colKey = isset($colKeyArr[$c])?$colKeyArr[$c]:$c;
$rowDatas[$row][$colKey] = iconv("gb2312", "utf-8", $data[$c]); //需要转码
}
$row++;
}
fclose($handle);
}else{
die('文件不存在');
}
unset($rowDatas[1]);
$mongo = new MongoClient();
$db = $mongo->mytestdb;
$table = $db->ebaysku2;
$res = $table->batchInsert($rowDatas);
echo '新增数据成功,'.count($rowDatas).'。共耗时:'.(microtime(true)-$startTime);
echo PHP_EOL;
print_r($res);
}
没有对比就没有伤害
2、PHPExcel或SpreadSheet导入数据
#前提是导入PHPExcel或 SpreadSheet
public function actionImportexceldata()
{
set_time_limit(0);
// error_reporting(E_ALL & ~E_NOTICE);
ini_set('memory_limit','8024M');
$startTime = microtime(true);
// $inputFileName = 'logapi/read/sku1.xlsx';
$inputFileName = 'logapi/read/sku1.csv'; //不能获取中文
try {
$spreadSheet = new SpreadSheet();
$objPHPExcel = $spreadSheet::load($inputFileName);
// $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
// $objReader = PHPExcel_IOFactory::createReader($inputFileType);
// $objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
die('加载文件发生错误:"' . pathinfo($inputFileName, PATHINFO_BASENAME) . '":' . $e->getMessage());
}
// 确定要读取的sheet
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); //取得一共有多少行
$highestColumn = $sheet->getHighestColumn(); //取得最大的列号
$highestColumnNum = PHPExcel_Cell::columnIndexFromString($highestColumn); // 列号转列数
$colKeyArr = ['sku','product_status','quantity_way','quantity_available'];
// 获取行的数据
$rowDatas = [];
for ($row = 2; $row <= $highestRow; $row++) { //$row定义从第几行开始读数据
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
for ($col = 0; $col < count($rowData[0]); $col++){
$colKey = isset($colKeyArr[$col])?$colKeyArr[$col]:$col;
$rowDatas[$row][$colKey] = $rowData[0][$col];
}
}
$mongo = new MongoClient();
$db = $mongo->mytestdb;
$table = $db->ebaysku;
$res = $table->batchInsert($rowDatas);
echo '新增数据成功,'.count($rowDatas).'。共耗时:'.(microtime(true)-$startTime);
echo PHP_EOL;
print_r($res);
}