我使用此代码从PHP生成Excel文件。 它工作正常,但生成的文件是一个过时的Excel版本2.0,最新的Excel客户端以只读方式打开它。
你能建议一个解决方案吗?
我正在寻找调整此代码的解决方案,而不是使用其他方法,例如PHPExcel
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
}
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
}
function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
}
function xlsWriteLabel($Row, $Col, $Value) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
}
// prepare headers information
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=\"export_".date("Y-m-d").".xls\"");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
// start exporting
xlsBOF();
// first row
xlsWriteLabel(0, 0, "id");
xlsWriteLabel(0, 1, "name");
xlsWriteLabel(0, 2, "email");
// second row
xlsWriteNumber(1, 0, 230);
xlsWriteLabel(1, 1, "John");
xlsWriteLabel(1, 2, "john@yahoo.com");
// third row
xlsWriteNumber(2, 0, 350);
xlsWriteLabel(2, 1, "Mark");
xlsWriteLabel(2, 2, "mark@yahoo.com");
// end exporting
xlsEOF();
答案 0 :(得分:4)
我使用PHPExcel类(https://github.com/PHPOffice/PHPExcel)创建各种版本的Excel表格。
对我来说非常好。
修改强>
虽然您同时更改了问题,但不想使用phpexcel,如果您使用PHPExcel,我将在下面举例说明代码的外观。只需添加上面链接中的类文件即可使其工作:
<?php
$oExcel = new PHPExcel();
// first row
$oExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 1, 'id');
$oExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 1, 'name');
$oExcel->getActiveSheet()->setCellValueByColumnAndRow(2, 1, 'email');
// second row
$oExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 2, 230);
$oExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 2, 'John');
$oExcel->getActiveSheet()->setCellValueByColumnAndRow(2, 2, 'john@yahoo.com');
// third row
$oExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 2, 350);
$oExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 2, 'Mark');
$oExcel->getActiveSheet()->setCellValueByColumnAndRow(2, 2, 'mark@yahoo.com');
$objWriter = PHPExcel_IOFactory::createWriter($oExcel, 'Excel5');
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="export_'. date('Y-m-d').'.xls"');
header("Pragma: no-cache");
header("Expires: 0");
$objWriter->save('php://output');