我正在尝试将文件导出为php中的Excel。我得到的文件为.xls
,但所有内容都放在由逗号(,)分隔的单列中,甚至每列的标题也都带有逗号分隔符的单列。这是我为实现导出excel文件编写的代码:
$db = $USER_DB->getDb();
$output = fopen('php://output', 'w');
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=template_demo.xls");
$today = date('d/m/y');
$lastDate = date('d/m/y', strtotime("-1 months"));
fputcsv($output, ['Date:',$today]);
fputcsv($output, ['Export for total Period:',"$lastDate - $today"]);
fputcsv($output, ['']);
fputcsv($output, ['No','Name','grade','achievement','Certification']);
$userSQL = "Select * from xyz where new = 1";
$users = $db->executeDb($userSQL);
foreach($users as $user){
fputcsv($output,$user);
}
代码内有什么问题?感谢您的帮助。
编辑
将PHPSpreadsheet与以下代码一起使用:
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->setCellValue('A1' , "No");
$spreadsheet->getActiveSheet()->setCellValue('B1' , "Name");
$spreadsheet->getActiveSheet()->setCellValue('C1' , "Grade");
$spreadsheet->getActiveSheet()->setCellValue('D1' , "Achievement");
$spreadsheet->getActiveSheet()->setCellValue('E1' , "Certification");
$userSQL = "Select * from xyz where new = 1";
$users = $db->executeDb($userSQL);
$rowcount = 2;
foreach($results as $i=>$row){
$spreadsheet->getActiveSheet()->setCellValue('A'.$rowcount, $row->no);
$spreadsheet->getActiveSheet()->setCellValue('B'.$rowcount, $row->name);
$spreadsheet->getActiveSheet()->setCellValue('C'.$rowcount, $row->grade);
$spreadsheet->getActiveSheet()->setCellValue('D'.$rowcount, $row->achievement);
$spreadsheet->getActiveSheet()->setCellValue('E'.$rowcount, $row->certification);
$rowcount++;
}
$writer = new Xlsx($spreadsheet);
$writer->save('user_template_demo.xlsx');
当我运行该应用程序时,将下载一个名为“ user_template.csv”而不是“ user_template_demo.xlsx”的空白文件,并且该文件为空。