0

I am trying to use PHPExcel lib. I already read some the API, but still didn't figure how to use it correctly.

I'm trying to convert an array, to an excel table.

If I have:

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

So the output in the excel file will be:

key1              key2

Content1          Content2
Content3          Content4

key1 and key2 as headings.

Can you help? Thank you

Novak
  • 2,760
  • 9
  • 42
  • 63
  • Look at the post: http://stackoverflow.com/questions/5545406/php-excel-data-looping Hope this helps! – lexeme Jul 10 '12 at 10:13
  • 1
    Can you have different key values in the different sub-arrays? If the subarrays are always identical, then the logic is pretty simple, otherwise the answer is rather more complicated. – Mark Baker Jul 14 '12 at 09:25

2 Answers2

0

Some discussions are here. check it Example

Sibiraj PR
  • 1,481
  • 1
  • 10
  • 25
0

Here is my code what I did it ...but the scenario here is little different, here the input is the excel file whereas the output is array of array in 'key' => 'value' pairs (as in your case it is vice versa) which is not much of a solution but though it might help you get going.

    <?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>';

So,in your case instead of using all get methods such as getCellByColumnAndRow as in my example you can use

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

You can make help of this resources also Tutorial here

CheatSheet here

pritesh
  • 2,162
  • 18
  • 24