PHP生成.xlsx

时间:2016-06-22 03:56:24

标签: 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;

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

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

正在寻找合适的代码1小时,但我找不到解决方案。

提前致谢。

8 个答案:

答案 0 :(得分:13)

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

编辑: PHPExcel已弃用,您也可以在GitHub上使用它的超级PHPSpreadsheet。 PhpSpreadsheet

答案 1 :(得分:7)

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');

答案 2 :(得分:4)

正如其他人所提到的,PhpSpreadsheet为此提供了一个不错的库。假设您拥有installed via 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);
}

示例用法:

$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);

答案 3 :(得分:2)

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

作为建议,如果你可以改变你的内容,你可以尝试一下吗?

$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;

答案 4 :(得分:1)

如果使用旧版本的PHP,您仍然可以使用早期版本的PHPSpreadsheet。

在项目目录中安装PHPSpreadsheet时必须包含其版本号。

这对我有用:

撰写者需要phpoffice / phpspreadsheet:1.8.0

答案 5 :(得分:0)

可能是该文件与使用的Excel版本不兼容。 尝试更改您的文件扩展名&#39; xlsx&#39;到&#x; xls并检查它是否正常工作。 如果它正常工作,则此文件扩展名(.xlsx)与您使用的Excel版本不兼容。

答案 6 :(得分:0)

尝试了几种选择之后,我发现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 repository


这是一个可行的示例,在3个工作表(标签)上展示了一些功能:

  1. 首先创建一个名为xlsxwriter.class.php的文件,其中包含找到的 here 代码。

  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();
    

更多信息:

答案 7 :(得分:-1)

查看我的代码,这里我制作了简单的xlsx文件

<?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>";
?>

对我而言,它运作良好。