简体   繁体   English

如何读取/写入/修改大型 Excel XLSB/XLSM 文件? (C#)

[英]How To Read/Write/Modify Large Excel XLSB/XLSM Files? (C#)

I have a 500mb excel (.xlsb/.xlsm) file.我有一个 500mb 的 excel (.xlsb/.xlsm) 文件。 I need a way to read/write/modify large (.xlsb/.xlsm) files using C# without loading the entire file in memory, but load it in chunks instead or at least load a single sheet at a time.我需要一种使用 C# 读取/写入/修改大型 (.xlsb/.xlsm) 文件的方法,而无需将整个文件加载到内存中,而是以块的形式加载它,或者至少一次加载一张纸。

Excel files are essentially zip files containing XML files. Excel文件本质上是包含XML文件的zip文件。 If you open an excel file with any zip tool you will see the contents of the excel document. 如果使用任何zip工具打开excel文件,您将看到excel文档的内容。 What you need to modify there is: 您需要修改的是:

  • xl/sharedStrings.xml - excel optimizes string usage by indexing them in this file (not visually, but you can iterate them to the end and count - the first one has an index 0, the second one has an index 1 and so on...). xl / sharedStrings.xml -excel通过在此文件中为它们建立索引来优化字符串使用(不是直观地进行索引,但是您可以迭代它们到末尾并计数)-第一个索引为0,第二个索引为1,依此类推。 ..)。 Use these indices to change/add strings in the sheet files to not corrupt the document. 使用这些索引可以更改/添加图纸文件中的字符串,而不会损坏文档。

  • xl/workbook.xml - contains sheets' names. xl / workbook.xml-包含工作表的名称。 For example you can find that sheet1 is named "This Months' Income" in excel. 例如,您可以在Excel中找到sheet1被命名为“本月收入”。 Use that to find your sheet by name if you will. 如果可以的话,使用它来按名称查找工作表。

  • xl/worksheets/*.xml - here are your actual sheets. xl / worksheets / *。xml-这是您的实际工作表。 To change/add a string use the shared strings XML file. 要更改/添加字符串,请使用共享字符串XML文件。 To change/add numbers do it directly. 要更改/添加数字,请直接执行。 Cells that contain a shared string value are marked as such. 包含共享字符串值的单元格将被标记为此类。

Now you just have to parse/edit these XML files while reading them line by line and not loading the entire files in memory and you will be able to process huge amounts of data with very little memory footprint. 现在,您只需要解析/编辑这些XML文件,同时逐行读取它们,而不是将整个文件加载到内存中,就可以用很少的内存占用空间处理大量数据。

In C# I use ZipArchive to temporary extract only the files I need, edit them and then update the zip. 在C#中,我使用ZipArchive临时仅提取我需要的文件,对其进行编辑,然后更新zip。 Do not extract everything and then zip it again because you will corrupt the file. 不要提取所有内容,然后再次压缩它,因为这将损坏文件。 At least I don't know how to zip it In such a way that will make it usable again. 至少我不知道如何压缩它,以使其再次可用。

真正快速读取和写入 xlsb/xlsx 可以通过https://github.com/KrzysztofDusko/SpreadSheetTasks完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM