codeigniter PHP_XLSXWriter和代码引发器损坏的输出Excel文件

y3bcpkx1  于 2022-12-07  发布在  PHP
关注(0)|答案(1)|浏览(106)

我正在尝试将[PHP_XLSXWriter](https://github.com/mk-j/PHP_XLSXWriter)与代码触发器集成
这是我的控制器源代码

public function ToExcel(){
    include_once APPPATH.'/third_party/xlsxwriter.class.php';
    $filename = "report-".date('d-m-Y-H-i-s').".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'); 

    $styles = array('widths'=>[3,20,30,40], 'font'=>'Arial','font-size'=>10,'font-style'=>'bold', 'fill'=>'#eee', 'halign'=>'center', 'border'=>'left,right,top,bottom');
    $styles2 = array( ['font'=>'Arial','font-size'=>10,'font-style'=>'bold', 'fill'=>'#eee', 'halign'=>'left', 'border'=>'left,right,top,bottom','fill'=>'#ffc'],['fill'=>'#fcf'],['fill'=>'#ccf'],['fill'=>'#cff'],);

    $header = array(
    'No 1'=>'string',
    'No 2'=>'string',
    'No 3'=>'string',
    'No 4'=>'string',
    );

    $writer = new XLSXWriter();
    $writer->setAuthor('Human');
    $writer->writeSheetHeader('Sheet1', $header, $styles);
    for($no=1;$no<=10;$no++){
        $writer->writeSheetRow('Sheet1', [$no, $no, $no, $no], $styles2);
    }
    $writer->writeToStdOut();   
}

Excel文件生成下载成功,但我尝试用Ms Excel打开时,显示文件已损坏,问题是原来生成的Excel文件的源代码处有一行空白

删除那一空行后,可以打开,没有任何问题
而且,如果我将控制器代码复制到单个php文件(没有涉及Code Igniter),脚本和生成的Excel文件就像一个魅力
如何删除第一个空行?
非常感谢你的帮助

at0kjp5o

at0kjp5o1#

您可以在 AJAX 上下载:

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

$rows = array(
    array('2003','1','-50.5','2010-01-01 23:00:00','2012-12-31 23:00:00'),
    array('2003','=B1', '23.5','2010-01-01 00:00:00','2012-12-31 00:00:00'),
);

$writer = new XLSXWriter();
$writer->setAuthor('Some Author'); 

//$writer->writeToFile('example.xlsx');
//echo $writer->writeToString();
// создаём файл
ob_start();
foreach($rows as $row)
    $writer->writeSheetRow('Sheet1', $row);
$writer->writeToStdOut();
$xlsData = ob_get_contents();
ob_end_clean();
$response =  array(
    'status' => TRUE,
    'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
);

die(json_encode($response));

相关问题