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

2024-09-25 00:20:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用openpyxl=2.3.3在django中将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文件。但对于microsoftexcel,它会显示警告,文件在打开时需要修复。在

我尝试用OpenXML SDK打开损坏的文件,这是验证结果:

enter image description here

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

enter image description here

所以在spreadsheetml/2006/main中似乎不存在的结构。Microsoft Excel发出验证警告,只需添加“忽略”即可。也有不正确的XFID:

enter image description here

我目前使用的是python2.7和openpyxl2.3.3,由于某些原因目前无法升级到3.0。你能建议一些解决办法或一些手动配置,以避免来自Excel的警告。在


Tags: 文件django警告示例responsexlsxexcel中将
1条回答
网友
1楼 · 发布于 2024-09-25 00:20:28

我发现了问题: 文件docProps/核心.xml在openpyxl读写之后似乎发生了变化。在

我通过添加pre模块、解压缩和存储docProps添加了一个解决方法/核心.xml. 在导出之前通过openpyxl处理后,我解压并用原始文件覆盖这个文件。在

它对我有效,Excel不再显示验证错误。在

更新:不正确的零件来自核心.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:已创建'或'dcterms:已修改“相反。在

然后我跟踪这个“{http://purl.org/dc/terms/}}创建的”它真的返回了dct:已创建。所以可能不是openpyxl bug而是这个dublin core bug。在

相关问题 更多 >