本文介绍了使用PHPExcel下载文件时获取损坏的xls文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的项目中,我使用PHPExcel 1.7.8将数据导出到excel.按照建议,我已在项目中成功配置了它并成功生成了xls文件并存储了它,但是当我尝试下载xls文件时,我gor损坏了xls文件而未收到任何错误消息.我有以下相同的代码.

In my current project, I used PHPExcel 1.7.8 for exporting data into excel. As per suggested I successfully configured it in my project and successfully generate xls file and stored it but when I tried to download xls file then I gor corrupted xls file without getting any error message. I have following code for the same.

/** Error reporting */
if (PHP_SAPI == 'cli')
     die('This example should only be run from a Web Browser');

/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
      ->setLastModifiedBy("Maarten Balliauw")
      ->setTitle("PHPExcel Test Document")
      ->setSubject("PHPExcel Test Document")
      ->setDescription("Test document for PHPExcel, generated using PHP classes.")
      ->setKeywords("office PHPExcel php")
      ->setCategory("Test result file");

// Add some data
$objPHPExcel->setActiveSheetIndex(0)
         ->setCellValue('A1', 'Hello')
         ->setCellValue('B1', 'world!')
         ->setCellValue('C1', 'Hello')
         ->setCellValue('D1', 'world!');

// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A2', 'Miscellaneous glyphs')
            ->setCellValue('B2', 'This is test text by me');

// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

// Redirect output to a client’s web browser (Excel5)
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"filename.xls\"");
header("Cache-Control: max-age=0");

// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save(str_replace('.php', '.xls', __FILE__));
$objWriter->save("php://output");
exit;

谢谢.

推荐答案

可以尝试吗?在您的

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"filename.xls\"");
header("Cache-Control: max-age=0");

放入ob_end_clean();.

您的输出缓冲区可能有问题.

There might be something wrong about your output buffer.

这篇关于使用PHPExcel下载文件时获取损坏的xls文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:42