Quantcast
Channel: PHPExcel Forum Rss Feed
Viewing all articles
Browse latest Browse all 2707

New Post: Why is the cell data duplicated in each column?

$
0
0
There are several ways to do this...
Considering that you ask mysql_fetch_array you return an associative array, you can retrieve the field names using array_keys then iterate in this array to write your headers.
Use a flag to do so only once when you course records.
$rowID=2//header in row 1, so first data in row 2
$writeHeader=true;
foreach($sheet as $rowArray)
{
    if($writeHeader){
        $hArray=array_keys($rowArray);
        $ColumnIdx=0; //column A, row for header hardcoded to 1
        foreach($hArray as $aHeader){
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($ColumnIdx++, 1, $aHeader);
        }
        $writeHeader=false;
    }
    $columnID = 'A';
    foreach($rowArray as $columnValue)
    {
      $objPHPExcel->getActiveSheet()->setCellValue($columnID.$rowID, $columnValue);
      $columnID++;//Warning: if you go after Z, this don't work
    }
    $rowID++;
}
Not tested :-)
I use setCellValueExplicitByColumnAndRow for two reasons:
-Explicit because I consider that the header is composed only of strings (which is the implicit type of explicit ;-)
-ByColumnAndRow: to avoid (bad) calculations on the column.
As I indicated in note in the code, increment the column when it is in the form of letter can lead to errors. If it is necessary to have as well, use the functions of support of PHPExcel (PHPExcel_Cell::columnIndexFromString and PHPExcel_Cell::stringFromColumnIndex) to convert the string to integer, make operations, convert the integer to string.

In doing so, if the table is empty, there is not any header.

Viewing all articles
Browse latest Browse all 2707

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>