如何使用php xlsxwriter从mysql导出xlsx

时间:2017-03-31 02:08:30

标签: php excel export

我使用PHP_XLSXWriter类从mysql

导出xlsx
include_once('xlsxwriter.class.php');
$filename = "example.xlsx";
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');   
$query="my query here";
$result = mysql_query($query); 
$rows = mysql_fetch_assoc($result); 
$header = array(
  'ID'=>'integer',
  'Subject'=>'string',
  'Content'=>'string',
);
$writer = new XLSXWriter();
$writer->writeSheetHeader('Sheet1', $header);
foreach($rows as $row)
    $writer->writeSheetRow('Sheet1', $row);
//$writer->writeSheet($rows,'Sheet1', $header);//or write the whole sheet in 1 call 
$writer->writeToStdOut();
//$writer->writeToFile('example.xlsx');
//echo $writer->writeToString();
exit(0);

导出xlsx只有标题,没有数据,我的代码有什么问题?

2 个答案:

答案 0 :(得分:2)

最后,这些代码可以运作。

include_once('xlsxwriter.class.php');
    $filename = "example.xlsx";
    header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
    header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');   
    $query="my query here";
    $result = mysql_query($query); 
    $rows = mysql_fetch_assoc($result); 
    $header = array(
      'ID'=>'integer',
      'Subject'=>'string',
      'Content'=>'string',
    );
    $writer = new XLSXWriter();
    $writer->writeSheetHeader('Sheet1', $header);
    $array = array();
    while ($row=mysql_fetch_row($result))
    {
        for ($i=0; $i<mysql_num_fields($result); $i++ )
        {
        $array[$i] = $row[$i];
        //$array[$i] = strip_tag($row[$i],"<p> <b> <br> <a> <img>");
        }
        $writer->writeSheetRow('Sheet1', $array);
    };

    //$writer->writeSheet($array,'Sheet1', $header);//or write the whole sheet in 1 call    

    $writer->writeToStdOut();
    //$writer->writeToFile('example.xlsx');
    //echo $writer->writeToString();
    exit(0);

答案 1 :(得分:0)

试试这个https://github.com/WeiB71/table2excel

function exportTableToExcel(tableName,fileName) {
    var table2excel = new Table2Excel();
    table2excel.export($("#" + tableName), fileName);
}