PHP生成.xlsx

ang*_*nod 7 php excel export

我正在生成扩展名为.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;
Run Code Online (Sandbox Code Playgroud)

但是当我打开生成的文件时出现错误.

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

一直在寻找正确的代码1小时,但我找不到解决方案.

提前致谢.

Ser*_*kin 17

SimpleXLSXGen

$books = [
    ['ISBN', 'title', 'author', 'publisher', 'ctry' ],
    [618260307, 'The Hobbit', 'J. R. R. Tolkien', 'Houghton Mifflin', 'USA'],
    [908606664, 'Slinky Malinki', 'Lynley Dodd', 'Mallinson Rendel', 'NZ']
];
$xlsx = SimpleXLSXGen::fromArray( $books );
$xlsx->saveAs('books.xlsx');
//  $xlsx->downloadAs('books.xlsx');
Run Code Online (Sandbox Code Playgroud)

  • 需要一个快速、简单的解决方案将数组写入 XLSX,这正好符合要求。完美的。谢谢谢尔盖! (2认同)

Dre*_*rew 16

你不能只创建一个没有库.请仔细阅读这篇PHPExcel Github,它应该指向正确的方向.

编辑: PHPExcel是DEPRECATED,您可以在GitHub上使用它的成功PHPSpreadsheet.PhpSpreadsheet

  • 我知道这是一个老问题,但PHPExcel已弃用,您可以在GitHub上使用它的超级PHPSpreadsheet.https://github.com/PHPOffice/PhpSpreadsheet (3认同)

bil*_*oah 5

正如其他人提到的,PhpSpreadsheet 为此提供了一个不错的库。假设您通过 composer 安装了它并且vendor/autoload.php已包含在您的项目中,您可以使用下面的函数从数组数组生成一个xlsx。我在此处包含了大量注释,以帮助向初学者介绍 PhpSpreadsheet 的工作原理以及代码的作用:

function writeXLSX($filename, $rows, $keys = [], $formats = []) {
    // instantiate the class
    $doc = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $doc->getActiveSheet();

    // $keys are for the header row.  If they are supplied we start writing at row 2
    if ($keys) {
        $offset = 2;
    } else {
        $offset = 1;
    }

    // write the rows
    $i = 0;
    foreach($rows as $row) {
        $doc->getActiveSheet()->fromArray($row, null, 'A' . ($i++ + $offset));
    }

    // write the header row from the $keys
    if ($keys) {
        $doc->setActiveSheetIndex(0);
        $doc->getActiveSheet()->fromArray($keys, null, 'A1');
    }

    // get last row and column for formatting
    $last_column = $doc->getActiveSheet()->getHighestColumn();
    $last_row = $doc->getActiveSheet()->getHighestRow();

    // autosize all columns to content width
    for ($i = 'A'; $i <= $last_column; $i++) {
        $doc->getActiveSheet()->getColumnDimension($i)->setAutoSize(TRUE);
    }

    // if $keys, freeze the header row and make it bold
    if ($keys) {
        $doc->getActiveSheet()->freezePane('A2');
        $doc->getActiveSheet()->getStyle('A1:' . $last_column . '1')->getFont()->setBold(true);
    }
    
    // format all columns as text
    $doc->getActiveSheet()->getStyle('A2:' . $last_column . $last_row)->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);
    if ($formats) {
        // if there are user supplied formats, set each column format accordingly
        // $formats should be an array with column letter as key and one of the PhpOffice constants as value
        // https://phpoffice.github.io/PhpSpreadsheet/1.2.1/PhpOffice/PhpSpreadsheet/Style/NumberFormat.html
        // EXAMPLE:
        // ['C' => \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_00, 'D' => \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_00]
        foreach ($formats as $col => $format) {
            $doc->getActiveSheet()->getStyle($col . $offset . ':' . $col . $last_row)->getNumberFormat()->setFormatCode($format);
        }
    }

    // write and save the file
    $writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($doc);
    $writer->save($filename);
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

$rows = [
    ['sku' => 'A123', 'price' => '99'],
    ['sku' => 'B456', 'price' => '5.35'],
    ['sku' => 'C789', 'price' => '17.7']
];
$keys = array_keys(current($rows));
$formats = ['B' => \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_00];

writeXLSX('pricelist.xlsx', $rows, $keys, $formats);
Run Code Online (Sandbox Code Playgroud)


ash*_*awg 5

在尝试了几个选项后,我发现这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
Run Code Online (Sandbox Code Playgroud)

(改编自图书馆的GitHub 存储库


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

  1. 首先创建一个名为的文件,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();
    
    Run Code Online (Sandbox Code Playgroud)

更多信息: