在 django 中使用 openpyxl=2.3.3 生成 excel 文件作为 HttpResponse 时出现问题。
示例代码:
# I just simply read a file and export
wb = load_workbook('test.xlsx') # WorkBook object.
ws = wb.get_active_sheet()
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8')
response['Content-Disposition'] = 'attachment; filename="test1.xlsx"'
response.write(save_virtual_workbook(wb))
libreOffice可以正常打开excel文件。但是对于 Microsoft excel,它会在打开时显示文件需要修复的警告。
我尝试通过 OpenXML SDK 打开损坏的文件,这是验证结果:
然后我比较了原始文件和准备文件(左边是损坏的文件):
因此,在 spreadsheetml/2006/main 中似乎不存在该结构。 Microsoft Excel 发出验证警告并向其添加“忽略”。还有不正确的 xfIds:
我目前使用的是 python 2.7 和 openpyxl 2.3.3,由于某种原因目前无法升级到 3.0。您能否建议一些解决方法或一些手动配置以避免来自 Excel 的警告。
最佳答案
我发现了问题: 文件docProps/core.xml似乎在openpyxl读写后发生了变化。
我通过添加预模块、解压缩和存储 docProps/core.xml 来解决这个问题。 在导出前用openpyxl处理后,我解压并用原来的文件覆盖了这个文件。
它对我有用,Excel 不再显示验证错误。
更新:core.xml 中的错误部分:
<dct:created xmlns:dct="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="dcterms:W3CDTF">2016-06-30T14:08:36Z</dct:created>
<dct:modified xmlns:dct="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="dcterms:W3CDTF">2019-08-28T13:46:19Z</dct:modified>
应该改为“dcterms:created”或“dcterms:modified”。
然后我跟踪这个'{ http://purl.org/dc/terms/ }created' 它真的返回 dct:created。所以可能不是 openpyxl 错误,而是这个都柏林核心错误。
关于python - openpyxl生成的Excel文件打开时需要修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57784018/