如何使用Python将XML文件导入Excel XLS文件模板? [英] How to import an XML file into an Excel XLS file template using Python?
问题描述
我有一个Excel模板文件,该文件具有XML定义的列.手动,我可以右键单击模板,然后右键单击XML>导入,然后选择XML文件,最后保存该文件.
I have an Excel template file which has columns as defined within an XML. Manually I can right click over the template then XML > import, and select the XML file, and finally save the file.
我如何执行此任务,然后自动使用Python对其进行编程?
XML文件示例:
<DCPowerFlow>
<branches>
<branch>
<busFrom name="bus_one" number="1" />
<busTo name="bus_two" number="2" />
<id>1</id>
<rateA>1000</rateA>
<resultPowerFlow>
<probOverFlow>0.0</probOverFlow>
<maxOverFlow>800</maxOverFlow>
</resultPowerFlow>
</branch>
<branch>
<busFrom name="bus_two" number="2" />
<busTo name="bus_three" number="3" />
<id>1</id>
<rateA>1200</rateA>
<resultPowerFlow>
<probOverFlow>0.1</probOverFlow>
<maxOverFlow>1300</maxOverFlow>
</resultPowerFlow>
</branch>
</branches>
</DCPowerFlow>
要检查手动任务,请执行以下操作:
To check for the manual task:
- 将以上示例另存为XML文件.
- 要创建Excel XLS模板,您可以简单地使用Excel打开上述XML示例,确保模板上没有数据(如果在导入中添加了任何数据,则删除数据)并将文件另存为XLS.
- 导入示例XML文件.右键单击创建的Excel模板文件,然后单击XML>导入,然后选择XML示例文件.
- 将包含数据的模板另存为新的XLS.
所以我需要做的是自动执行第3步和第4步.
推荐答案
最后,我可以使用 win32com.client
模块弄清楚这一点.
Finally I could figure this out using win32com.client
module.
我成功使用以下代码将xml导入到我用作模板的现有Excel xlsx文件中,然后将其保存为其他名称:
I used the following code successfully to import an xml to an existing Excel xlsx file I use as template, and then save it with a different name:
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open("D:/tmp/template.xlsx")
wb.XmlImport("D:/tmp/result.xml")
wb.SaveAs("D:\\tmp\\result.xlsx")
wb.Close()
可以在此处找到Excel工作簿的方法.另外我还必须考虑到 saveAs
方法不支持正斜杠.
Methods for Excel workbooks can be found here. Also I had to take into account that the saveAs
method doesn't support forward slashes.
这篇关于如何使用Python将XML文件导入Excel XLS文件模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!