PHP将Excel导入数据库(xls& xlsx)

时间:2012-07-12 08:33:09

标签: php excel import

我试图搜索一些插件将Excel文件导入MySQL数据库,其中一个是http://code.google.com/p/php-excel-reader/

该工具功能强大,可将整个excel内容显示为html。

但是,我想我只需要读取Excel文件并将内容提取到一个数组中,然后编写一个SQL语句进入数据库。

有没有好的代码和包裹?谢谢!

5 个答案:

答案 0 :(得分:36)

这是最好的插件,包含适当的文档和示例

https://github.com/PHPOffice/PHPExcel

加点:你可以在discussion forum寻求帮助,你会在一天之内得到作者本人的回复,真是令人印象深刻。

答案 1 :(得分:15)

有时我需要将大型xlsx文件导入数据库,因此我使用spreadsheet-reader因为它可以读取每行文件。它是非常内存效率高的导入方式。

<?php
    // If you need to parse XLS files, include php-excel-reader
    require('php-excel-reader/excel_reader2.php');

    require('SpreadsheetReader.php');

    $Reader = new SpreadsheetReader('example.xlsx');
    // insert every row just after reading it
    foreach ($Reader as $row)
    {
        $db->insert($row);
    }
?>

https://github.com/nuovo/spreadsheet-reader

答案 2 :(得分:7)

如果您在处理之前可以将.xls转换为.csv,则可以使用以下查询将csv导入数据库:

load data local infile 'FILE.CSV' into table TABLENAME fields terminated by ',' enclosed by '"' lines terminated by '\n' (FIELD1,FIELD2,FIELD3)

答案 3 :(得分:3)

如果将excel文件保存为CSV文件,则可以使用PHPMyAdmin等工具将其导入mysql数据库

我不确定这对你的情况是否有帮助,但手动或编程的csv文件解析到数据库要比我想象的excel文件容易得多。

编辑:我会建议查看其他答案,而不是我的,因为@diEcho答案似乎更合适。

答案 4 :(得分:1)

我写了一个继承的类:

<?php
class ExcelReader extends Spreadsheet_Excel_Reader {	
	
 function GetInArray($sheet=0) {

  $result = array();

   for($row=1; $row<=$this->rowcount($sheet); $row++) {
    for($col=1;$col<=$this->colcount($sheet);$col++) {
     if(!$this->sheets[$sheet]['cellsInfo'][$row][$col]['dontprint']) {
      $val = $this->val($row,$col,$sheet);
      $result[$row][$col] = $val;
     }
    }
   }
  return $result;
 }

}
?>

所以我可以这样做:

<?php

 $data = new ExcelReader("any_excel_file.xls");
 print_r($data->GetInArray());

?>