Joe*_*eph 5 php phpexcel yii2 phpexcelreader
我正在开发一个 Yii2 API,我需要上传一个 .csv 或 .xlsx 文件并使用 PHPExcel 读取它(现在已弃用,但我坚持使用它,因为新的 PhpSpreadsheet 需要 PHP 5.6 或更高版本)并返回数组数据的 。
这是 API 函数中使用的代码
public function actionUpload()
{
$params = $_FILES['uploadFile'];
if($params)
{
$data = array();
$model = new UploadForm();
$model->uploadFile = $_FILES['uploadFile'];
$file = UploadedFile::getInstanceByname('uploadFile');
$inputFileName = $model->getpath($file,$data);
// Read your Excel workbook
try
{
$inputFileType = \PHPExcel_IOFactory::identify($inputFileName['link']);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
if($inputFileType == 'CSV')
{
if (mb_check_encoding(file_get_contents($inputFileName['link']), 'UTF-8'))
{
$objReader->setInputEncoding('UTF-8');
}
else
{
$objReader->setInputEncoding('Windows-1255');
//$objReader->setInputEncoding('ISO-8859-8');
}
}
$objPHPExcel = $objReader->load($inputFileName['link']);
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputFileName['link'],PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$fileData = array();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
array_push($fileData,$rowData[0]);
// Insert row data array into your database of choice here
}
return $fileData;
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我们上传包含希伯来语数据的 excel 文件时存在编码问题。如您所见,上面代码中的以下代码用于解决此问题
if (mb_check_encoding(file_get_contents($inputFileName['link']), 'UTF-8'))
{
$objReader->setInputEncoding('UTF-8');
}
else
{
$objReader->setInputEncoding('Windows-1255');
}
Run Code Online (Sandbox Code Playgroud)
后来我发现, UTF-8并且Windows-1255不是为可被上传但其它编码等苍蝇的唯一可能的编码UTF-16或其他的,这取决于用户的操作系统。除了使用mb_check_encoding之外,还有什么更好的方法可以找到编码
读取文件中数据的过程中常见的错误是:
iconv(): Detected an illegal character in input string
Run Code Online (Sandbox Code Playgroud)
如您所见,由于无法检测到文件的适当编码,会出现上述错误。有什么解决方法吗?
小智 0
确保首先清理页面中的输出缓冲区:
ob_end_clean();
header( "Content-type: application/vnd.ms-excel" );
header('Content-Disposition: attachment; filename="uploadFile.xls"');
header("Pragma: no-cache");
header("Expires: 0");
ob_end_clean();
Run Code Online (Sandbox Code Playgroud)