由于PHPExcel已经不再维护,PhpSpreadsheet是PHPExcel的下一个版本。PhpSpreadsheet是一个用纯PHP编写的库,并引入了命名空间,PSR规范等。这里简单介绍下PhpSpreadsheet的导入导出功能。
1.使用composer安装:
composer require phpoffice/phpspreadsheet
2.GitHub下载:
https://github.com/PHPOffice/PhpSpreadsheet
下载好的放入vendor下PhpOffice
use PhpOffice\PhpSpreadsheet\IOFactory;
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
前端页面:
控制器:
public function import()
{
//获取表格的大小,限制上传表格的大小5M
if(isset($_FILES['inputExcelclass'])){
$file_size = $_FILES['inputExcelclass']['size'];
if ($file_size > 5 * 1024 * 1024) {
$this->error('文件大小不能超过5M');
exit();
}
}
//限制上传表格类型
if(isset($_FILES['inputExcelclass'])){
$fileExtendName = substr(strrchr($_FILES['inputExcelclass']["name"], '.'), 1);
}
//application/vnd.ms-excel 为xls文件类型
if ($fileExtendName != 'xls' && $fileExtendName != 'xlsx') {
$this->error('必须为excel表格,且必须为xls格式!');
exit();
}
// 有Xls和Xlsx格式两种
if( $fileExtendName =='xlsx' )
{
$objReader = IOFactory::createReader('Xlsx');
}else{
$objReader = IOFactory::createReader('Xls');
}
$objReader->setReadDataOnly(TRUE);
$filename = $_FILES['inputExcelclass']['tmp_name'];
$objPHPExcel = $objReader->load($filename); //$filename可以是上传的表格,或者是指定的表格
$sheet = $objPHPExcel->getSheet(0); //excel中的第一张sheet
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
\PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
$lines = $highestRow -1;
if($lines <= 0){
$this->error('excel表格,没有数据!');
}
//循环读取excel表格,整合成数组。如果是不指定key的二维,就用$data[i][j]表示。
for ($j = 2; $j <= $highestRow; $j++) {
$data[$j - 2] = [
'did' => trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue()),
'hid' => trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue()),
'h_name' => trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue()),
'name' => trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue()),
'Semester' => trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue()),
'create_time' => ($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue()-25569)*24*60*60,
'end_time' => ($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue()-25569)*24*60*60,
];
}
$class = new ClassModel();
$res = $class->saveAll($data);
if ($res) {
$this->success('上传成功!');
}
}
注:PHP 的时间函数是从1970-1-1日开始计算的,单位是秒数。但是 EXCEL的是从1900-1-1日开始算的单位是天数。
这里的create_time列在Excel格式这样的,发现获取到的却是浮点型43110,以后查资料才知道在Excel中时间格式默认常规格式下,读取出都为浮点型,所以我们要将其转换下.
先获得 EXCEL中 1970-1-1 代表的数字,我查了是25569。
把excel中的43110,在php中用函数正确的显示出来
$time = (43110 – 25569) * 24 *60 *60; //获得秒数
前端页面:
导出
控制器
public function export(){
$newExcel = new Spreadsheet(); //创建一个新的excel文档
$objSheet = $newExcel->getActiveSheet(); //获取当前操作sheet的对象
//设置宽度为true,不然太窄了
$newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
//获取数据库的数据。
$List = $class->where('status','1')->order(['hid' => 'desc'])->select();
$objSheet->setTitle('班级表'); //设置当前sheet的标题
//设置第一栏的标题
$objSheet->setCellValue('A1', '系D')
->setCellValue('B1', '班D');
foreach ($List as $k => $val) {
$k = $k + 2;
$objSheet->setCellValue('A' . $k, $val['did'])
->setCellValue('B' . $k, $val['hid']);
}
$this->downloadExcel($newExcel, '表1', 'Xls');
}
//公共文件,用来传入xls并下载
function downloadExcel($newExcel, $filename, $format)
{
// $format只能为 Xlsx 或 Xls
if ($format == 'Xlsx') {
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
} elseif ($format == 'Xls') {
header('Content-Type: application/vnd.ms-excel');
}
header("Content-Disposition: attachment;filename="
. $filename . date('Y-m-d') . '.' . strtolower($format));
header('Cache-Control: max-age=0');
$objWriter = IOFactory::createWriter($newExcel, $format);
$objWriter->save('php://output');
//通过php保存在本地的时候需要用到
//$objWriter->save($dir.'/demo.xlsx');
//以下为需要用到IE时候设置
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
exit;
}