gpt4 book ai didi

php - 使用 PhpSpreadsheet 将数据数组导出到 xlsx 文件的问题

转载 作者:行者123 更新时间:2023-12-04 20:34:50 28 4
gpt4 key购买 nike

大家好,我的项目中的每个人,我正在尝试将数据从数据库导出到 xlsx 文件,但我没有得到正确的数据。我附上了数据的图像。 enter image description here

我正在使用以下代码。

    use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xls;

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

$exportArray = array();
$query = mysqli_query($conn, "select * from table");

if(mysqli_num_rows($query) > 0){

while ($row = mysqli_fetch_assoc($query)) {

$exportArray[$exp]['id'] = $row['id'];
$exportArray[$exp]['name'] = $row['name'];
$exportArray[$exp]['address'] = $row['address'];

$exp++;

}

}
$array = array();

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

$sheet->setCellValue('A1', 'id');
$sheet->setCellValue('B1', 'name');
$sheet->setCellValue('C1', 'address');

$rowCount = 2;
foreach ($exportArray as $value) {

$sheet->setCellValue('A' . $rowCount, $value['id']);
$sheet->setCellValue('B' . $rowCount, $value['name']);
$sheet->setCellValue('C' . $rowCount, $value['address']);
$rowCount++;
}

$fileName = 'test123.xls';
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'. $fileName .'.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit();

当我使用以下代码查看工作表数据时
$sheetData = $sheet->toArray(null, true, true, true);

print_r($sheetData);

我得到了正确的输出。一切看起来都很好,但我不明白,为什么我在工作表中以错误的格式获取数据?

最佳答案

添加此 use PhpOffice\PhpSpreadsheet\IOFactory;
现在使用下面的代码导出Xlsx格式的数据

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="test.xlsx"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Cache-Control: cache, must-revalidate');
header('Pragma: public');

$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');

关于php - 使用 PhpSpreadsheet 将数据数组导出到 xlsx 文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57107147/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com