【问题标题】:How to read data from excel using with PHPExcel如何使用 PHPExcel 从 excel 中读取数据
【发布时间】:2014-10-12 05:17:57
【问题描述】:

我正在尝试从 Excel 工作表 (.xlsx) 导入数据。我找到了PHPExcel 用于导入数据,但是在下载文档和源代码后,我很困惑哪个文件对我很重要。我也尝试在那个网站上查找文档,但没有找到方法。

关于我的任务:从选定的工作表中读取 excel 工作表数据并将数据插入到我的数据库表中。

如果你能指导我如何使用它,我真的很感激。

谢谢。

【问题讨论】:

    标签: php phpexcel


    【解决方案1】:

    您可以使用 PHPExcel 库读取 Excel 文件并将数据插入数据库。

    示例代码如下。

    //  Include PHPExcel_IOFactory
    include 'PHPExcel/IOFactory.php';
    
    $inputFileName = 'sample.xls';
    
    //  Read your Excel workbook
    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
    } catch(Exception $e) {
        die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
    }
    
    //  Get worksheet dimensions
    $sheet = $objPHPExcel->getSheet(0); 
    $highestRow = $sheet->getHighestRow(); 
    $highestColumn = $sheet->getHighestColumn();
    
    //  Loop through each row of the worksheet in turn
    for ($row = 1; $row <= $highestRow; $row++){ 
        //  Read a row of data into an array
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                        NULL,
                                        TRUE,
                                        FALSE);
        //  Insert row data array into database here using your own structure
    

    【讨论】:

    • 比将整个工作表传输到 PHP 数组更好的答案;依次迭代每一行,因此您只需要处理一小部分数据,并且不会超出 PHP 的内存限制
    • 如果您事先知道数据的格式,例如用户上传,在我自己的情况下,您可以将$highestColumn设置为最后一列数据,例如$highestColumn = 'E'。这很有用,因为您的数据库通常会有固定的列。
    【解决方案2】:

    通过快速浏览文档,使用 IOFactory 自动确定文件格式。

    include 'path/to/PHPExcel/IOFactory.php';
    
    // Let IOFactory determine the spreadsheet format
    $document = PHPExcel_IOFactory::load('path/to/spreadsheet.xls');
    
    // Get the active sheet as an array
    $activeSheetData = $document->getActiveSheet()->toArray(null, true, true, true);
    
    var_dump($activeSheetData);
    

    【讨论】:

      【解决方案3】:

      试试这个,这样你就可以开始开发过程了:

      include '.... /PHPexcel/Classes/PHPExcel.php';
          $dataFfile = "C:/tmp/test_data.xls";
          $objPHPExcel = PHPExcel_IOFactory::load($dataFfile);
          $sheet = $objPHPExcel->getActiveSheet();
          $data = $sheet->rangeToArray('A2:AB5523');
          echo "Rows available: " . count($data) . "\n";
          foreach ($data as $row) {
              print_r($row);
          }
      

      将包含路径替换为 PHPExcel.php 的路径
      $dataFile 替换为您的 excel 文件
      还要调整要导入的单元格的范围

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多