python - openpyxl生成的Excel文件打开时需要修复

标签 python excel openpyxl

在 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 打开损坏的文件,这是验证结果:

enter image description here

然后我比较了原始文件和准备文件(左边是损坏的文件):

enter image description here

因此,在 spreadsheetml/2006/main 中似乎不存在该结构。 Microsoft Excel 发出验证警告并向其添加“忽略”。还有不正确的 xfIds:

enter image description here

我目前使用的是 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/

相关文章:

c++ - VBA 调用 C++ DLL - 错误 48(找不到文件)

arrays - VBA - 数组中的自定义数字格式 - 特定数组编号后出现错误

python - openpyxl:无需迭代即可将值或格式应用于一系列 Excel 单元格

python - 在 openpyxl 中,如何移动或复制带有格式、合并单元格、公式和超链接的单元格范围

python - 将全局变量传递给类和函数的替代方法

python - Django unicode 连接

javascript - 快速傅里叶变换Javascript

python - Python tkinter 的视频播放器,当我暂停视频时,我无法重新播放

c# - 如何使用 NPOI 读取文件

python - 迭代 xlsx 文件并删除 unicode python openpyxl