使用 PHPExcel 保存时文件格式无效
Invalid file format when saving with PHPExcel
$file = '{full path and filename}';
//Read file
$file_type = PHPExcel_IOFactory::identify( $file );
$excel_reader = PHPExcel_IOFactory::createReader($file_type);
$this->php_excel = $excel_reader->load($file);
//Set some values
$this->php_excel->setActiveSheetIndex(0);
$this->php_excel->getActiveSheet()->SetCellValue('A1', 'Hello');
$this->php_excel->getActiveSheet()->SetCellValue('B2', 'world!');
$this->php_excel->getActiveSheet()->SetCellValue('C1', 'Hello');
$this->php_excel->getActiveSheet()->SetCellValue('D2', 'world!');
//Write to file new location
$excel_writer = PHPExcel_IOFactory::createWriter($this->php_excel, 'Excel2007' );
$excel_writer->save('c:\test.xls');
c:\test.xls
已创建,但我在尝试加载 Excel 文件时遇到错误(来自 OpenOffice,但我认为这不是问题所在)。我正在阅读的文件约为 260kb,而创建的 test.xls 约为 64kb。它说无效,OpenOffice 在打开文件失败时尝试修复文件。
我做错了什么?
感谢@Mark Baker,我发现我可以将创建 Writer 的行更改为:
//Given that the file that are going to be saved should be of the same
//format that the read file has.
$excel_writer = PHPExcel_IOFactory::createWriter($this->php_excel, $file_type );
$file = '{full path and filename}';
//Read file
$file_type = PHPExcel_IOFactory::identify( $file );
$excel_reader = PHPExcel_IOFactory::createReader($file_type);
$this->php_excel = $excel_reader->load($file);
//Set some values
$this->php_excel->setActiveSheetIndex(0);
$this->php_excel->getActiveSheet()->SetCellValue('A1', 'Hello');
$this->php_excel->getActiveSheet()->SetCellValue('B2', 'world!');
$this->php_excel->getActiveSheet()->SetCellValue('C1', 'Hello');
$this->php_excel->getActiveSheet()->SetCellValue('D2', 'world!');
//Write to file new location
$excel_writer = PHPExcel_IOFactory::createWriter($this->php_excel, 'Excel2007' );
$excel_writer->save('c:\test.xls');
c:\test.xls
已创建,但我在尝试加载 Excel 文件时遇到错误(来自 OpenOffice,但我认为这不是问题所在)。我正在阅读的文件约为 260kb,而创建的 test.xls 约为 64kb。它说无效,OpenOffice 在打开文件失败时尝试修复文件。
我做错了什么?
感谢@Mark Baker,我发现我可以将创建 Writer 的行更改为:
//Given that the file that are going to be saved should be of the same
//format that the read file has.
$excel_writer = PHPExcel_IOFactory::createWriter($this->php_excel, $file_type );