excel学习库

excel表格_excel函数公式大全_execl从入门到精通

PhpSpreadsheet读取excel文件内容,与xlsx格式转成csv格式

程序使用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));

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

«    2024年12月    »
1
2345678
9101112131415
16171819202122
23242526272829
3031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
    文章归档
      友情链接