【问题标题】:How to open an Excel file with PHPExcel for both reading and writing?如何使用 PHPExcel 打开 Excel 文件进行读写?
【发布时间】:2012-01-10 00:29:08
【问题描述】:

我正在使用 PHPExcel 库,并且正在创建用于写入或读取的 xls 对象:

PHPExcel_IOFactory::createReaderForFile('file.xlsx')
PHPExcel_IOFactory::createWriter('Excel2007')

如何打开 XLSX 文件进行读写?

【问题讨论】:

    标签: php phpexcel


    【解决方案1】:

    您使用读取器和 load() 方法将文件加载到 PHPExcel,然后使用写入器和 save() 方法保存该文件...但是 PHPExcel 本身不知道 PHPExcel 对象的来源...它不关心您是从文件(或什么类型的文件)加载它还是手动创建它。

    因此,没有“打开读/写”的概念。您只需按名称读取文件,然后保存到相同的文件名。这将用您在脚本中所做的任何更改覆盖原始文件。

    编辑

    例子

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

    我可以建议您阅读文档,并查看 /Tests 中的示例代码

    【讨论】:

    • 你能写示例代码来解释这个吗?我不明白当您谈到 using a reader and the load() method, then save that file using a writer and the save() method 时,您是在谈论两个不同的对象(一个读者,一个作家),但我需要打开文件,修改一些单元格并将同一个对象保存到文件中。
    • 这会导致“允许的内存大小为 xxxx 字节耗尽”,可以修复吗?
    • 通过查看记录在案的内存处理建议和建议(例如使用单元缓存)可能会解决此问题
    • 谢谢@MarkBaker。
    • 完美运行!
    猜你喜欢
    • 2015-02-16
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多