from openpyxl import load_workbook wb = load_workbook('file.xlsx') ws = wb['Sheet1']
有什么方法可以检索表示ws对象的xml代码吗?注意:我想避免使用zipfile模块。相反,我尝试从ws直接提取xml。我阅读了openpyxl的源代码,并在玩lxml-没有成功。
ws
zipfile
openpyxl
lxml
7cwmlq891#
我自己想出来的。您可以在保存工作簿时捕获XML,而不是通过解压缩保存的工作簿来提取XML。wb.save方法使用了ExcelWriter类,我修改了这个类以适应这个目的:
wb.save
ExcelWriter
import openpyxl from openpyxl.writer.excel import * class MyExcelWriter(openpyxl.writer.excel.ExcelWriter): def write_worksheet(self, ws): ws._drawing = SpreadsheetDrawing() ws._drawing.charts = ws._charts ws._drawing.images = ws._images if self.workbook.write_only: if not ws.closed: ws.close() writer = ws._writer else: writer = WorksheetWriter(ws) writer.write() ws._rels = writer._rels # my addition starts here if ws.title == 'My Sheet': with open(writer.out, 'r', encoding='utf8') as file: xml_code = file.read() # my code continues here... # my addition ends here self._archive.write(writer.out, ws.path[1:]) self.manifest.append(ws) writer.cleanup() openpyxl.writer.excel.ExcelWriter = MyExcelWriter
write_worksheet函数创建一个临时xml文件,其路径存储在writer.out中。记住from <module> import *is considered bad practice-谨慎使用。
write_worksheet
writer.out
from <module> import *
1条答案
按热度按时间7cwmlq891#
我自己想出来的。您可以在保存工作簿时捕获XML,而不是通过解压缩保存的工作簿来提取XML。
wb.save
方法使用了ExcelWriter
类,我修改了这个类以适应这个目的:write_worksheet
函数创建一个临时xml文件,其路径存储在writer.out
中。记住
from <module> import *
is considered bad practice-谨慎使用。