2012-07-09 39 views
0

我正在尝试使用PHPExcel库。我已经阅读了一些API,但仍然没有确定如何正确使用它。PHPExcel使用示例

我想将一个数组,转换为Excel表。

如果我有:

$Array = array(
       array('key1' => 'Content1', 'key2' => 'Content2'), 
       array('key1' => 'Content3', 'key2' => 'Content4') 
); 

所以在Excel文件输出将是:

key1    key2 

Content1   Content2 
Content3   Content4 

key1key2作为标题。

你能帮忙吗?谢谢

+0

看看帖子:http://stackoverflow.com/questions/5545406/php-excel-data-looping 希望这会有所帮助! – lexeme 2012-07-10 10:13:56

+1

你可以在不同的子数组中使用不同的键值吗?如果子阵列总是相同的,那么逻辑非常简单,否则答案会更复杂。 – 2012-07-14 09:25:22

回答

0

有些讨论在这里。检查 Example

0

这里是我的代码是什么我做到了......但这里的情况是有点不同,这里的输入是excel文件,而输出为阵列中的“关键”阵列=> '价值'对(在你的情况下,反之亦然),这不是一个解决方案,但它可能会帮助你走。

<?php 

    include './PHPExcel/IOFactory.php'; 
    $objPHPExcel = PHPExcel_IOFactory::load('campaign.xlsx'); 

    foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) { 

    $highestColumn = $worksheet->getHighestDataColumn(); 

    //Getting highest column with data 
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); 

    //Getting highest row with data 
    $highestRow = $worksheet->getHighestRow(); 

    $header = []; 
    //For saving all heading from Excel file. 
    for($i = 0 ; $i <= $highestColumnIndex ; $i++) 
    { 
     $cell = $worksheet->getCellByColumnAndRow($i,1); 
     $val = $cell->getValue(); 

     $header[] = $val; 

    } 

    $completeArray = []; 
    $value = []; 

    //For saving header and value pairs in a array 
    for ($row = 2; $row <= $highestRow; ++ $row) { 

     for ($col = 0; $col < $highestColumnIndex; ++ $col) { 
      $cell = $worksheet->getCellByColumnAndRow($col, $row); 
      $val = $cell->getValue(); 

      $value[$header[$col]] = $val; 
     } 

     //Inserting that array... 
     $completeArray[] = $value; 

    } 

} 

echo '<pre>'; 
print_r($completeArray); 
echo '</pre>'; 

所以,你的情况,而不是使用所有get方法,如getCellByColumnAndRow在我的例子中,你可以使用

setCellValueByColumnAndRow($column, $row, $value); 

可以使这种资源的帮助,也 教程here

CheatSheet here