2012-03-14 103 views
94

我有一個php應用程序,我想從excel中讀取數據,插入到數據庫中,然後爲特定用戶生成pdf報告。 我在網上搜索了很多,但沒有具體給出這兩件事。如果有人能夠提供教程或其他內容,那將是一個真正的幫助。如何使用phpexcel讀取數據並插入數據庫?

+0

你有沒有把你的excel數據導出到CSV?您的數據中是否有消除CSV的選項? – 2012-03-14 03:58:57

+2

你看過PHPExcel庫嗎? – 2012-03-14 07:24:36

+0

@MarkBaker我還沒有看到過這個庫,儘管我的確嘗試過檢查函數參考文件,但由於太大而無法查看,因爲除了項目的其他部分之外,我必須儘快完成此工作。 – coder101 2012-03-19 12:55:32

回答

187

使用PHPExcel圖書館閱讀的Excel文件,並將數據傳送到數據庫

// Include PHPExcel_IOFactory 
include 'PHPExcel/IOFactory.php'; 

$inputFileName = './sampleData/example1.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 your database of choice here 
} 

再說了變得很依賴你的數據庫,以及如何你想在它的結構

+0

謝謝。有效。 – coder101 2012-07-13 08:46:20

+0

我今天用v 1.7.9測試了這個,2013-06-02,它沒有工作。我不得不用'$ sheet-> getHighestColumn()'替換'$ highestColumn = PHPExcel_Cell :: columnIndexFromString($ sheet-> getHighestColumn());''。你可能在代碼中有一個錯誤,因爲你試圖從字符串中獲取列索引 - 但是試圖通過$ highestColumn。$循環來訪問它(這隻會給一個奇怪的連接整數,如果你沒有使用字符) – user151496 2013-06-16 21:05:19

+0

最高列應該是列字母值;所以你是對的 - 這應該只是設置'$ highestColumn = $ sheet-> getHighestColumn();'而不是'$ highestColumn = PHPExcel_Cell :: columnIndexFromString($ sheet-> getHighestColumn());'我不可靠 ' – 2013-06-16 21:48:36

10

在數據爲了通過笨從Microsoft Excel 2007讀取的數據只是創建一個輔助函數excel_helper.php並添加以下內容:

 require_once APPPATH.'libraries/phpexcel/PHPExcel.php'; 
     require_once APPPATH.'libraries/phpexcel/PHPExcel/IOFactory.php'; 
     in controller add the following code to read spread sheet by active sheet 
    //initialize php excel first 
    ob_end_clean(); 
    //define cachemethod 
    $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp; 
    $cacheSettings = array('memoryCacheSize' => '20MB'); 
    //set php excel settings 
    PHPExcel_Settings::setCacheStorageMethod(
      $cacheMethod,$cacheSettings 
     ); 

    $arrayLabel = array("A","B","C","D","E"); 
    //=== set object reader 
    $objectReader = PHPExcel_IOFactory::createReader('Excel2007'); 
    $objectReader->setReadDataOnly(true); 

    $objPHPExcel = $objectReader->load("./forms/test.xlsx"); 
    $objWorksheet = $objPHPExcel->setActiveSheetIndexbyName('Sheet1'); 

    $starting = 1; 
    $end  = 3; 
    for($i = $starting;$i<=$end; $i++) 
    { 

     for($j=0;$j<count($arrayLabel);$j++) 
     { 
      //== display each cell value 
      echo $objWorksheet->getCell($arrayLabel[$j].$i)->getValue(); 
     } 
    } 
    //or dump data 
    $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true); 
    var_dump($sheetData); 

    //see also the following link 
    http://blog.mayflower.de/561-Import-and-export-data-using-PHPExcel.html 
    ----------- import in another style around 5000 records ------ 
    $this->benchmark->mark('code_start'); 
    //=== change php ini limits. ===== 
    $cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp; 
    $cacheSettings = array(' memoryCacheSize ' => '50MB'); 
    PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings); 
    //==== create excel object of reader 
    $objReader = PHPExcel_IOFactory::createReader('Excel2007'); 
    //$objReader->setReadDataOnly(true); 
    //==== load forms tashkil where the file exists 
    $objPHPExcel = $objReader->load("./forms/5000records.xlsx"); 
    //==== set active sheet to read data 
    $worksheet = $objPHPExcel->setActiveSheetIndexbyName('Sheet1'); 


    $highestRow   = $worksheet->getHighestRow(); // e.g. 10 
    $highestColumn  = $worksheet->getHighestColumn(); // e.g 'F' 
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); 
    $nrColumns   = ord($highestColumn) - 64; 
    $worksheetTitle  = $worksheet->getTitle(); 

    echo "<br>The worksheet ".$worksheetTitle." has "; 
    echo $nrColumns . ' columns (A-' . $highestColumn . ') '; 
    echo ' and ' . $highestRow . ' row.'; 
    echo '<br>Data: <table border="1"><tr>'; 
    //----- loop from all rows ----- 
    for ($row = 1; $row <= $highestRow; ++ $row) 
    { 
     echo '<tr>'; 
     echo "<td>".$row."</td>"; 
     //--- read each excel column for each row ---- 
     for ($col = 0; $col < $highestColumnIndex; ++ $col) 
     { 
      if($row == 1) 
      { 
       // show column name with the title 
       //----- get value ---- 
       $cell = $worksheet->getCellByColumnAndRow($col, $row); 
       $val = $cell->getValue(); 
       //$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val); 
       echo '<td>' . $val ."(".$row." X ".$col.")".'</td>'; 
      } 
      else 
      { 
       if($col == 9) 
       { 
        //----- get value ---- 
        $cell = $worksheet->getCellByColumnAndRow($col, $row); 
        $val = $cell->getValue(); 
        //$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val); 
        echo '<td>zone ' . $val .'</td>'; 
       } 
       else if($col == 13) 
       { 
        $date = PHPExcel_Shared_Date::ExcelToPHPObject($worksheet->getCellByColumnAndRow($col, $row)->getValue())->format('Y-m-d'); 
        echo '<td>' .dateprovider($date,'dr') .'</td>'; 
       } 
       else 
       { 
        //----- get value ---- 
        $cell = $worksheet->getCellByColumnAndRow($col, $row); 
        $val = $cell->getValue(); 
        //$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val); 
        echo '<td>' . $val .'</td>'; 
       } 
      } 
     } 
     echo '</tr>'; 
    } 
    echo '</table>'; 
    $this->benchmark->mark('code_end'); 

    echo "Total time:".$this->benchmark->elapsed_time('code_start', 'code_end');  
    $this->load->view("error"); 
3
 if($query) 
     { 
     // try to export to excel the whole data --- 
     //initialize php excel first 
     ob_end_clean(); 
     //--- create php excel object --- 
     $objPHPExcel = new PHPExcel(); 
     //define cachemethod 
     ini_set('memory_limit', '3500M'); 
     $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp; 
     $cacheSettings = array('memoryCacheSize' => '800MB'); 
     //set php excel settings 
     PHPExcel_Settings::setCacheStorageMethod(
       $cacheMethod,$cacheSettings 
      ); 


     $objPHPExcel->getProperties()->setTitle("export")->setDescription("none"); 

     $objPHPExcel->setActiveSheetIndex(0); 

     // Field names in the first row 
     $fields = $query->list_fields(); 
     $col = 0; 
     foreach ($fields as $field) 
     { 
      $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field); 
      $col++; 
     } 

     // Fetching the table data 
     $row = 2; 
     foreach($query->result() as $data) 
     { 
      $col = 0; 
      foreach ($fields as $field) 
      { 
       $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field); 
       $col++; 
      } 

      $row++; 
     } 

     $objPHPExcel->setActiveSheetIndex(0); 
     //redirect to cleint browser 
     header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
     header('Content-Disposition: attachment;filename=Provinces.xlsx'); 
     header('Cache-Control: max-age=0'); 

     $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); 
     $objWriter->save('php://output'); 
    } 
+0

謝謝。其實我在幾個月前發佈了這個問題,並且有一個解決方法,就是時間本身。但下次我將使用這個功能時,我一定會使用你的建議。再次感謝。 – coder101 2013-01-13 08:55:15

+3

什麼是'query' – shorif2000 2013-11-06 14:34:57

+0

看來db對象 – 2017-05-03 05:48:48

2
if($this->mng_auth->get_language()=='en') 
      { 
        $excel->getActiveSheet()->setRightToLeft(false); 
      } 
       else 
       { 
        $excel->getActiveSheet()->setRightToLeft(true); 
       } 

     $styleArray = array(
       'borders' => array(
        'allborders' => array(
         'style' => PHPExcel_Style_Border::BORDER_THIN, 
          'color' => array('argb' => '00000000'), 
        ), 
       ), 
      ); 

      //SET property 
      $objPHPExcel->getActiveSheet()->getStyle('A1:M10001')->applyFromArray($styleArray); 


    $objPHPExcel->getActiveSheet()->getStyle('A1:M10001')->getAlignment()->setWrapText(true); 


$objPHPExcel->getActiveSheet()->getStyle('A1:'.chr(65+count($fields)-1).$query->num_rows())->applyFromArray($styleArray); 

$objPHPExcel->getActiveSheet()->getStyle('A1:'.chr(65+count($fields)-1).$query->num_rows())->getAlignment()->setWrapText(true); 
1

這裏是最近的答案,從文件中這樣一個問題:07reader.php

<?php 


error_reporting(E_ALL); 
ini_set('display_errors', TRUE); 
ini_set('display_startup_errors', TRUE); 

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />'); 

date_default_timezone_set('Europe/London'); 

/** Include PHPExcel_IOFactory */ 
require_once '../Classes/PHPExcel/IOFactory.php'; 


if (!file_exists("05featuredemo.xlsx")) { 
    exit("Please run 05featuredemo.php first." . EOL); 
} 

echo date('H:i:s') , " Load from Excel2007 file" , EOL; 
$callStartTime = microtime(true); 

$objPHPExcel = PHPExcel_IOFactory::load("05featuredemo.xlsx"); 

$callEndTime = microtime(true); 
$callTime = $callEndTime - $callStartTime; 
echo 'Call time to read Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL; 
// Echo memory usage 
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true)/1024/1024) , " MB" , EOL; 


echo date('H:i:s') , " Write to Excel2007 format" , EOL; 
$callStartTime = microtime(true); 

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); 
$objWriter->save(str_replace('.php', '.xlsx', __FILE__)); 

$callEndTime = microtime(true); 
$callTime = $callEndTime - $callStartTime; 

echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL; 
echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL; 
// Echo memory usage 
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true)/1024/1024) , " MB" , EOL; 


// Echo memory peak usage 
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true)/1024/1024) , " MB" , EOL; 

// Echo done 
echo date('H:i:s') , " Done writing file" , EOL; 
echo 'File has been created in ' , getcwd() , EOL; 
1

使用PHPExcel庫,下面的代碼就可以了。

require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';  
$objReader = PHPExcel_IOFactory::createReader('Excel2007'); 
$objReader->setReadDataOnly(true); //optional 

$objPHPExcel = $objReader->load(__DIR__.'/YourExcelFile.xlsx'); 
$objWorksheet = $objPHPExcel->getActiveSheet(); 

$i=1; 
foreach ($objWorksheet->getRowIterator() as $row) { 

    $column_A_Value = $objPHPExcel->getActiveSheet()->getCell("A$i")->getValue();//column A 
    //you can add your own columns B, C, D etc. 

    //inset $column_A_Value value in DB query here 

    $i++; 
} 
相關問題