TP5使用phpexce上传导入csv文件
程序员文章站
2024-03-21 14:37:04
...
前端上传使用layui.upload组件,具体参考Layui手册
php:
//主逻辑
//限制上传表格类型
$file_type = $_FILES['excel_import']['type'];
if ($file_type!='application/vnd.ms-excel') {
return [RESULT_ERROR,'上传失败,只能上传excel表格!'];
}
if (is_uploaded_file($_FILES['excel_import']['tmp_name'])) {//判断文件上传是否成功
$data = get_excel_data($_FILES['excel_import']['tmp_name'],2,0,'csv');
//TODO 执行导入后的逻辑
}else{
return [RESULT_ERROR, '请选择文件后导入'];
}
//get_excel_data
/**
* 读取excel返回数据
*/
function get_excel_data($file_url = '', $start_row = 1, $start_col = 0, $type = 'xls')
{
vendor('phpoffice/phpexcel/Classes/PHPExcel');
//此处逻辑为解决导入xls和csv的冲突
if( $type=='xlsx'||$type=='xls' ){
$objPHPExcel = PHPExcel_IOFactory::load($file_url);
}else if( $type=='csv' ){
$objReader = PHPExcel_IOFactory::createReader('CSV')
->setDelimiter(',')
->setInputEncoding('GBK') //不设置将导致中文列内容返回boolean(false)或乱码
->setEnclosure('"')
->setSheetIndex(0);
$objPHPExcel = $objReader->load($file_url);
}else{
die('Not supported file types!');
}
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestDataRow();
$highestColumn = $objWorksheet->getHighestDataColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$excel_data = [];
for ($row = $start_row; $row <= $highestRow; $row++)
{
for ($col = $start_col; $col < $highestColumnIndex; $col++)
{
$excel_data[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
}
}
return $excel_data;
}