当前位置:Gxlcms > PHP教程 > phpExcel读取excel文件

phpExcel读取excel文件

时间:2021-07-01 10:21:17 帮助过:23人阅读

之前的博文已经对PHPExcel导出excel文件做了简单的总结,现对他读取excel做以下总结。(对数据量不会很大的建可以采用web直接用此方法读取,如果数据量会很大的话,还是建议web只做上传功能,读取、处理还是放后台吧。PHPExcel还是比较耗费时间、内存的。)

实例代码:

  1. //首先导入PHPExcel
  2. require_once 'PHPExcel.php';
  3. $filePath = "test.xlsx";
  4. //建立reader对象
  5. $PHPReader = new PHPExcel_Reader_Excel2007();
  6. if(!$PHPReader->canRead($filePath)){
  7. $PHPReader = new PHPExcel_Reader_Excel5();
  8. if(!$PHPReader->canRead($filePath)){
  9. echo 'no Excel';
  10. return ;
  11. }
  12. }
  13. //建立excel对象,此时你即可以通过excel对象读取文件,也可以通过它写入文件
  14. $PHPExcel = $PHPReader->load($filePath);
  15. /**读取excel文件中的第一个工作表*/
  16. $currentSheet = $PHPExcel->getSheet(0);
  17. /**取得最大的列号*/
  18. $allColumn = $currentSheet->getHighestColumn();
  19. /**取得一共有多少行*/
  20. $allRow = $currentSheet->getHighestRow();
  21. //循环读取每个单元格的内容。注意行从1开始,列从A开始
  22. for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){
  23. for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
  24. $addr = $colIndex.$rowIndex;
  25. $cell = $currentSheet->getCell($addr)->getValue();
  26. if($cell instanceof PHPExcel_RichText) //富文本转换字符串
  27. $cell = $cell->__toString();
  28. echo $cell;
  29. }
  30. }

这里需要说明的是上面注释中的“富文本转换字符串”。

PHPExcel读取EXCEl文件中,如果单元格中的内容有两种字体时,读到的是富文本的对象:

例如:单元格中有内容:“测试1”,其中前半部分的“测试”字体为宋体,后半部分的“1”字体为Calibri,这时候通过

$cell = $sheet->getCell($addr)->getValue();

获取单元格的值。并打印:

  1. PHPExcel_RichText Object(
  2. [_richTextElements:private] => Array
  3. (
  4. [0] => PHPExcel_RichText_TextElement Object ([_text:private] => 测试)
  5. [1] => PHPExcel_RichText_Run Object
  6. (
  7. [_font:private] => PHPExcel_Style_Font Object
  8. (
  9. [_name:private] => Calibri
  10. [_size:private] => 11
  11. [_bold:private] =>
  12. [_italic:private] =>
  13. [_superScript:private] =>
  14. [_subScript:private] =>
  15. [_underline:private] => none
  16. [_strikethrough:private] =>
  17. [_color:private] => PHPExcel_Style_Color Object
  18. (
  19. [_argb:private] => FF000000
  20. [_isSupervisor:private] =>
  21. [_parent:private] =>
  22. [_parentPropertyName:private] =>
  23. )
  24. [_parentPropertyName:private] =>
  25. [_isSupervisor:private] =>
  26. [_parent:private] =>
  27. [colorIndex] => 8
  28. )
  29. [_text:private] => 1
  30. )
  31. )
  32. )

可以看到对这样的单元格不能直接读取单元格的文本内容。(注:这里的富文本是我自己的翻译,不知对否)。

另外,读取单元格的函数还有:

//列从0开始,行从1开始

$currentSheet ->getCellByColumnAndRow($colIndex,$rowIndex)->getValue();

人气教程排行