通过文本和文件流保存 openpyxl 文件
我正在将 OpenPyXL 构建到一个应用程序中,该应用程序需要一个包含 excel 文件内容的字符串,以便通过文件流写入。
根据我对 OpenPyXL 源代码的调查,它看起来并不支持这种输出。有谁有修改 openpyxl 以支持这一点的经验吗?
或者有什么一般建议/解决方法吗?
谢谢。
I'm building OpenPyXL into an application that expects a string containing the content of the excel file, for it to write via file stream.
From my investigation into the OpenPyXL source code, it doesn't look like it supports this kind of output. Does anyone have any experience with modifying openpyxl to support this?
Or any general advice/workarounds?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 openpyxl 2.6 中,调用
save_virtual_workbook
方法会发出以下警告:在某些时候
save_virtual_workbook
将从 openpyxl 中删除。在 Python 3 中,将 openpyxl 工作簿保存到文件流的典型用法变为:
在查看 WorkBook
save
方法的实现之后,“文件名”被直接发送到 ZipFile,该 ZipFile 接受路径或类似文件对象,因此不需要 NamedTemporaryFile,只需使用内存中的 BytesIO:In openpyxl 2.6 calling the
save_virtual_workbook
method issues the following warning:At some point
save_virtual_workbook
will be removed from openpyxl.In Python 3 typical usage to save an openpyxl workbook to a filestream becomes:
After looking at the implementation of the WorkBook
save
method, the 'filename' is sent straight to ZipFile which accepts a path or file-like object so there is no need for a NamedTemporaryFile and simply use in-memory BytesIO:jcollado的答案实际上是有效的,但在 openpyxl.writer.excel 中还有一个名为“save_virtual_workbook”的函数(遗憾的是尚未记录),它将获取您的工作簿并将工作簿作为字符串返回:
您正在寻找的是字符串由 save_virtual_workbook() 返回
jcollado's answer is actually valid, but there is also a function (sadly not documented yet) called "save_virtual_workbook" in openpyxl.writer.excel that will take your workbook and return the workbook as a string:
What you're looking for is the string returned by save_virtual_workbook()
如何使用
StringIO
对象来保存文件的内容:您要查找的字符串就是本示例最后一行中打印的内容。
What about using a
StringIO
object to save the contents of the file:The string you're looking for is what is being printed in the last line of this example.
自版本 2.6 起,已弃用与
save_virtual_workbook
兼容的实现:A compatible implementation with
save_virtual_workbook
deprecated since version 2.6: