简体   繁体   English

像 Openpyxl 这样的模块如何创建/读取 Excel 文件

[英]How do Modules like Openpyxl create/read Excel files

tl;dr tl;博士
How to interact with Excel using Python, but without using pre defined modules.如何使用 Python 与 Excel 交互,但不使用预定义的模块。

I am working with Openpyxl Module in Python to read and write data from and to Excel.我正在使用 Python 中的 Openpyxl 模块从 Excel 读取数据和向 Excel 写入数据。 There are some methods which are not available in Openpyxl but are available in Xlsxwriter like folding of rows (folding of columns is possible in Openpyxl).有一些方法在 Openpyxl 中不可用,但在 Xlsxwriter 中可用,例如行折叠(在 Openpyxl 中可以折叠列)。 So I thought lets look at the source code and try to implement it myself.所以我想让我们看看源代码并尝试自己实现它。

But the first question I had was how do I interact with Excel using Python?但是我遇到的第一个问题是如何使用 Python 与 Excel 交互? How do these Modules read data from and write data to excel.这些模块如何从excel读取数据和向excel写入数据。

At a high level an xlsx file is a collection of XML files in a zip container.在较高级别上,xlsx 文件是 zip 容器中的 XML 文件的集合。 So xlsxwriter/openpyxl write XML files and then use the Python standard libary zip module to collect them into an xlsx file.所以 xlsxwriter/openpyxl 编写 XML 文件,然后使用 Python 标准库 zip 模块将它们收集到一个 xlsx 文件中。

Most Excel xlsx features are defined as XML elements or as a collection of elements.大多数 Excel xlsx 功能被定义为 XML 元素或元素的集合。 Options are defined as elements or element attributes.选项被定义为元素或元素属性。

However, and this is a big however, there are interactions between elements within a file and with other files that form part of the collection.然而,这是一个很大的问题,文件中的元素与构成集合一部分的其他文件之间存在交互。 So a lot of the work in xlsxwriter/openpyxl goes into ensuring that the interactions are correct and that they don't break other features.因此,xlsxwriter/openpyxl 中的很多工作都用于确保交互正确且不会破坏其他功能。 At least that is my experience and it is also why xlsxwriter has a large test suite with tests against full Excel generated files.至少这是我的经验,这也是 xlsxwriter 有一个大型测试套件的原因,其中包含针对完整 Excel 生成文件的测试。

So in order to extend one of these modules you will need to figure out the XML elements or attributes to be added and the interactions with other elements/files.因此,为了扩展这些模块之一,您需要弄清楚要添加的 XML 元素或属性以及与其他元素/文件的交互。

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

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