php 如何使用PHPExcel打开Excel文件进行读写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8797103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open an Excel file with PHPExcel for both reading and writing?
提问by Petruza
I'm using the PHPExcel library, and I'm creating xls objects either for writing or for reading:
我正在使用 PHPExcel 库,并且我正在创建用于写入或读取的 xls 对象:
PHPExcel_IOFactory::createReaderForFile('file.xlsx')
PHPExcel_IOFactory::createWriter('Excel2007')
PHPExcel_IOFactory::createReaderForFile('file.xlsx')
PHPExcel_IOFactory::createWriter('Excel2007')
How can I open an XLSX file for reading and writing?
如何打开 XLSX 文件进行读写?
回答by Mark Baker
You load a file into PHPExcel using a reader and the load() method, then save that file using a writer and the save() method... but PHPExcel itself is unaware of the source of the PHPExcel object... it doesn't care whether you have loaded it from a file (or what type of file) or created it by hand.
您使用读取器和 load() 方法将文件加载到 PHPExcel 中,然后使用编写器和 save() 方法保存该文件......但 PHPExcel 本身不知道 PHPExcel 对象的来源......它不知道不在乎您是从文件(或什么类型的文件)加载它或手动创建它。
As such, there is no concept of "opening for read/write". You simply read the file by name, and save to the same filename. That will overwrite the original file with any changes that you have made in your script.
因此,没有“打开读/写”的概念。您只需按名称读取文件,然后保存为相同的文件名。这将使用您在脚本中所做的任何更改覆盖原始文件。
EDIT
编辑
Example
例子
error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Europe/London');
set_include_path(get_include_path() . PATH_SEPARATOR . './Classes/');
include 'PHPExcel/IOFactory.php';
$fileType = 'Excel5';
$fileName = 'testFile.xls';
// Read the file
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);
// Change the file
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B1', 'World!');
// Write the file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->save($fileName);
And can I suggest that you read the documentation, and look at the sample code in /Tests
我是否建议您阅读文档,并查看 /Tests 中的示例代码