1.因為Phpexecel已經停止維護,所以要使用心得phpoffice;
2.注意引入
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
3.上代碼
/**
* 使用PHPoffice導入
*
* @param string $file 文件地址
* @param int $sheet 工作表sheet(傳0則獲取第一個sheet)
* @param int $columnCnt 列數(傳0則自動獲取最大列)
* @param array $options 操作選項
* array mergeCells 合並單元格數組
* array formula 公式數組
* array format 單元格格式數組
*
* @return array
* @throws Exception
*/
function importExecl($file = '', $sheet = 0, $columnCnt = 0, $options = [])
{
try {
$file = 'E:/fast/public/uploads/20190910/aeb86ef4be998d313886f6276879bb24.xls';
/* 轉碼 */
$file = iconv("utf-8", "gb2312", $file);
if (empty($file) OR !file_exists($file)) {
echo '文件不存在';
exit;
}
/** @var Xlsx $objRead */
$objRead = IOFactory::createReader('Xlsx');
if (!$objRead->canRead($file)) {
/** @var Xls $objRead */
$objRead = IOFactory::createReader('Xls');
if (!$objRead->canRead($file)) {
throw new \Exception('只支持導入Excel文件!');
}
}
/* 如果不需要獲取特殊操作,則只讀內容,可以大幅度提升讀取Excel效率 */
empty($options) && $objRead->setReadDataOnly(true);
/* 建立excel對象 */
$obj = $objRead->load($file);
/* 獲取指定的sheet表 */
$currSheet = $obj->getSheet($sheet);
if (isset($options['mergeCells'])) {
/* 讀取合並行列 */
$options['mergeCells'] = $currSheet->getMergeCells();
}
if (0 == $columnCnt) {
/* 取得最大的列號 */
$columnH = $currSheet->getHighestColumn();
/* 兼容原邏輯,循環時使用的是小於等於 */
$columnCnt = Coordinate::columnIndexFromString($columnH);
}
/* 獲取總行數 */
$rowCnt = $currSheet->getHighestRow();
$data = [];
/* 讀取內容 */
for ($_row = 1; $_row <= $rowCnt; $_row++) {
$isNull = true;
for ($_column = 1; $_column <= $columnCnt; $_column++) {
$cellName = Coordinate::stringFromColumnIndex($_column);
$cellId = $cellName . $_row;
$cell = $currSheet->getCell($cellId);
if (isset($options['format'])) {
/* 獲取格式 */
$format = $cell->getStyle()->getNumberFormat()->getFormatCode();
/* 記錄格式 */
$options['format'][$_row][$cellName] = $format;
}
if (isset($options['formula'])) {
/* 獲取公式,公式均為=號開頭數據 */
$formula = $currSheet->getCell($cellId)->getValue();
if (0 === strpos($formula, '=')) {
$options['formula'][$cellName . $_row] = $formula;
}
}
if (isset($format) && 'm/d/yyyy' == $format) {
/* 日期格式翻轉處理 */
$cell->getStyle()->getNumberFormat()->setFormatCode('yyyy/mm/dd');
}
$data[$_row][$cellName] = trim($currSheet->getCell($cellId)->getFormattedValue());
if (!empty($data[$_row][$cellName])) {
$isNull = false;
}
}
/* 判斷是否整行數據為空,是的話刪除該行數據 */
// if ($isNull) {
// unset($data[$_row]);
// }
}
return $data;
} catch (\Exception $e) {
throw $e;
}