如何使用 Phpspreadsheet 将数组直接写入 XSLS 文件
How to write an array directly into a XSLS file using Phpspreadsheet
我实际上使用 fputcsv
创建了我的数据库内容的 CSV 文件(一个基本的 select 查询)。它工作得很好。我现在不想创建一个 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');
$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)
);
我实际上使用 fputcsv
创建了我的数据库内容的 CSV 文件(一个基本的 select 查询)。它工作得很好。我现在不想创建一个 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');
$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)
);