如何使用 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.

有任何想法吗?

原文由 angel enanod 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 852
1 个回答

在尝试了几个选项后,我发现 PHP_XLSX_Writer 适合我的需要。

PHP_XLSX_Writer - …设计为轻量级,最小内存使用,生成XLSX格式的Excel兼容工作簿,支持基本功能:

>   - supports PHP 5.2.1+
>  - takes 'UTF-8' characters (or encoded input)
>  - multiple worksheets
>  - supports currency/date/numeric cell formatting, simple formulas
>  - supports basic cell styling
>  - supports writing huge 100K+ row spreadsheets
>
> ```

(改编自库的 [GitHub 存储库](https://github.com/mk-j/PHP_XLSXWriter))

* * *

**这是一个工作示例,** 展示了 3 个工作表(选项卡)上的一些功能:

1. 首先创建一个名为 `xlsxwriter.class.php` 的文件,其中包含 **[此处](https://raw.githubusercontent.com/mk-j/PHP_XLSXWriter/master/xlsxwriter.class.php)** 的代码。

2. 创建另一个 `PHP` 文件(在同一文件夹中),其中包含:


 require('xlsxwriter.class.php');
$fname='my_1st_php_excel_workbook.xlsx';
$header1 = [ 'create_date' => 'date',
             'quantity' => 'string',
             'product_id' => 'string',
             'amount' => 'money',
             'description' => 'string' ];
$data1 = [ ['2021-04-20', 1, 27, '44.00', 'twig'],
           ['2021-04-21', 1, '=C1', '-44.00', 'refund'] ];
$data2 = [ ['2','7','ᑌᑎIᑕᗝᗪᗴ ☋†Ϝ-➑'],
           ['4','8','😁'] ];
$styles2 = array( ['font-size'=>6],['font-size'=>8],['font-size'=>10],['font-size'=>16] );

$writer = new XLSXWriter();
$writer->setAuthor('Your Name Here');
$writer->writeSheet($data1,'MySheet1', $header1);  // with headers
$writer->writeSheet($data2,'MySheet2');            // no headers
$writer->writeSheetRow('MySheet2', $rowdata = array(300,234,456,789), $styles2 );

$writer->writeToFile($fname);   // creates XLSX file (in current folder)
echo "Wrote $fname (".filesize($fname)." bytes)<br>";

// ...or instead of creating the XLSX you can just trigger a
// download by replacing the last 2 lines with:

// header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// header('Content-Disposition: attachment;filename="'.$fname.'"');
// header('Cache-Control: max-age=0');
// $writer->writeToStdOut();

”`


更多信息:

原文由 ashleedawg 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题