【问题标题】:How to write an array directly into a XSLS file using Phpspreadsheet如何使用 Phpspreadsheet 将数组直接写入 XSLS 文件
【发布时间】:2020-03-27 17:55:11
【问题描述】:

我实际上使用fputcsv创建了一个包含我的数据库内容的 CSV 文件(一个基本的选择查询)。它运行良好。我现在不想创建一个 CSV,而是一个带有Phpspreadsheet 的 XSLX。我可以逐个单元格地插入值,但它没有经过优化。我在文档中找不到如何直接插入将被解释为完整行的数组。怎么做 ?这是我使用的代码:

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'My column 1');
$sheet->setCellValue('B1', 'My column 2');
$sheet->setCellValue('C1', 'My column 3');
$sheet->setCellValue('D1', 'My column 4');
$sheet->setCellValue('E1', 'My column 5');
$writer = new Xlsx($spreadsheet);

if (mysqli_num_rows($resultSQL)){
  $filename = 'MyFile.csv';
  $output_file = fopen($filename, 'w');
  fputcsv($output_file,array('My column 1','My column 2','My column 3','My column 4','My column 5')); // The old way I create my CSV
  while($line = $resultSQL->fetch_assoc()) {
    fputcsv($output_file, $line); // The old way to put all values of row in my CSV
    // How to do the same with PhpSpreadSheet ?
  }
$writer->save('MyFile.xlsx');

【问题讨论】:

    标签: php excel csv phpspreadsheet


    【解决方案1】:
    $arrayData = [
        [NULL, 2010, 2011, 2012],
        ['Q1',   12,   15,   21],
        ['Q2',   56,   73,   86],
        ['Q3',   52,   61,   69],
        ['Q4',   30,   32,    0],
    ];
    $spreadsheet->getActiveSheet()
        ->fromArray(
            $arrayData,  // The data to set
            NULL,        // Array values with this value will not be set
            'C3'         // Top left coordinate of the worksheet range where
                         // we want to set these values (default is A1)
        );
    

    https://phpspreadsheet.readthedocs.io/en/latest/topics/accessing-cells/#setting-a-range-of-cells-from-an-array

    【讨论】:

      猜你喜欢
      • 2018-11-05
      • 2018-07-18
      • 2021-01-01
      • 1970-01-01
      • 2011-10-31
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多