使用PHPExcel下载时获取损坏的xls文件

时间:2012-11-05 12:20:53

标签: php phpexcel

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

/** 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;

谢谢。

1 个答案:

答案 0 :(得分:1)

你能试试吗?就在你的

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

ob_end_clean();

输出缓冲区可能有问题。