
程序使用thinkphp5.1
1、安装
使用composer安装:
composer require phpoffice/phpspreadsheet
GitHub下载:
https://github.com/PHPOffice/PhpSpreadsheet
2、引用
:
use PhpOffice\PhpSpreadsheet\Reader\Xls;use PhpOffice\PhpSpreadsheet\IOFactory;use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
:
//读取xlsx文件内容public function readXlsx(Request $request){ $data = []; /*xlsx文件路径*/ $file_name = 'simple.xlsx'; /*编码转换*/ $file = iconv("utf-8", "gb2312", $file_name); $objRead = IOFactory::createReader('Xlsx'); $objRead->setReadDataOnly(true); /* 建立excel对象 */ $obj = $objRead->load($file); /* 获取指定的sheet表 */ $sheet = 0; $currSheet = $obj->getSheet($sheet); // 获取总行数 $count = $currSheet->getHighestRow(); /* 取得最大的列号 */ $columnH = $currSheet->getHighestColumn(); /* 兼容原逻辑,循环时使用的是小于等于 */ $columnCnt = Coordinate::columnIndexFromString($columnH); // 读取内容 $i=2表示从第二行读取,第一行为标题 for ($i = 2; $i <= $count; $i++) { $a = $currSheet->getCell('A'.$i)->getFormattedValue(); $data[] = $a; } return json($data);}
3、读取数据过大时内存溢出需要已下设置
ini_set("memory_limit","-1");
ini_set('max_execution_time',0);
4、xlsx格式转成csv格式
/*转格式文件*/$file_name ='simple.xlsx'; $fileold = iconv("utf-8", "gb2312", $file_name);/*读取源文件内容*/$objRead = IOFactory::createReader('Xlsx');$obj = $objRead->load($fileold);/*读取内容*/$objWriter = IOFactory::createWriter($obj,'Csv');$objWriter->save(str_replace('.xlsx', '.csv',$fileold));