简体   繁体   English

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

[英]How to export php array to excel file(.xlsx)?

I am currently working on exporting a php array to a .xlsx file.我目前正在将 php 数组导出到 .xlsx 文件。 And this is how the array looks like:这就是数组的样子:

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"}

I'd like to export this array to format like:我想将此数组导出为以下格式:

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

And this is what I have so far:这就是我到目前为止所拥有的:

$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);  

Yet, after executing this, it showed nothing on the excel .xlsx file.然而,执行此操作后,它在 excel .xlsx 文件中没有显示任何内容。 Is there anything missing above for writing data to an excel file?上面是否缺少将数据写入 excel 文件的任何内容?

can you try the below?你可以试试下面的吗? according to the doc , it retrieves the cell ( $pos ) and sets the value.根据doc ,它检索单元格( $pos )并设置值。

Make sure $pos has value as well确保$pos也有价值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM