PHP生成.xlsx

我生成扩展名为.xlsx的Excel文件

这是我生成的简单代码

$file = "test.xlsx"; header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment; filename='.$file); $content = "Col1\tCol2\tCol3\t\n"; $content .= "test1\ttest1\ttest3\t\n"; $content .= "testtest1\ttesttest2\ttesttest3\t\n"; echo $content; 

但是,当我打开生成的文件时,我得到一个错误。

Excel cannot open the file 'test.xlsx' because the file format or file extension is not valid.

一直在寻找正确的代码1小时,但我没有find解决办法。

提前致谢。

你将无法创build一个没有图书馆。 阅读这个PHPExcel Github应该指出你正确的方向。

该文件可能与所使用的Excel版本不兼容。 尝试将您的文件扩展名“xlsx”更改为“xls”,并检查它是否正常工作。 如果它正在工作,则此文件扩展名(.xlsx)与您使用的Excel版本不兼容。

内容不是有效的xlsx内容。 尝试将您的内容作为逗号分隔值内容发送,并使用xls打开

作为一个build议,如果你可以改变你的内容,可能你可以试试这个吗?

 $file = "test.csv"; header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment; filename='.$file); $content = "Col1,Col2,Col3\n"; $content .= "test1,test1,test3\n"; $content .= "testtest,ttesttest2,testtest3\n"; echo $content; 
 See my code , Here I have made simple xlsx file <?php include 'PHPExcel/PHPExcel.php'; include 'PHPExcel/PHPExcel/Writer/Excel2007.php'; $objPHPExcel = new PHPExcel(); $objPHPExcel->setActiveSheetIndex(0); $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello'); $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Trudeau'); $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Fernandes'); $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); $objWriter->save(str_replace('.php', '.xlsx', __FILE__)); echo " Click here for gerate xlsx file <a href='test.xlsx'>clicking me</a>"; ?> and for me, it's working fine.