如何将php数组导出到Excel文件(.xlsx)?

时间:2019-01-18 06:43:14

标签: php excel

我目前正在将php数组导出到.xlsx文件。这是数组的样子:

array(9) { [0]=> string(1) "1" [1]=> string(24) "Company" [2]=> string(9) " 12345689" [3]=> string(9) "Name" [4]=> string(1) "4" [5]=> string(26) "careerintern2017@gmail.com"}

我想将此数组导出为以下格式:

id | ent_name | ent_num  | owner | ent_c | email 
-------------------------------------------------------------------------
1  | Company  | 123456789| Name  | 4     | careerintern2017@gmail.com
-------------------------------------------------------------------------

这是我到目前为止所拥有的:

$excel_file_path = "ent_info/ent_info_list.xlsx";
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
$row_num = $spreadsheet->setActiveSheetIndex(0)->getHighestRow();
$row_num =$row_num+1;
$col_num=0;
$counter=1;
$sheet = $spreadsheet->getActiveSheet();
foreach($array as $data){
    $pos = get_excel_col($col_num).$row_num;
        //$pos = A2, B2, C2 .... (for example)
    $sheet->setCellValue($pos, $data);
    if($counter==6){
        $row_num++;
        $col_num=0;
    }
    $col_num++;
    $counter++;
}
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
$writer->save($excel_file_path);  

但是,执行此操作后,它在excel .xlsx文件上什么也没有显示。将数据写入excel文件时,上面是否缺少任何内容?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下吗?根据{{​​3}},它会检索单元格($pos)并设置值。

确保$pos也有价值

var_dump($pos);//just to see which cell it is
$spreadsheet->getActiveSheet()
    ->getCell($pos)
    ->setValue('Some value');