【问题标题】:Convert Excel zip file content to actual Excel file?将 Excel zip 文件内容转换为实际的 Excel 文件?
【发布时间】:2020-01-04 15:43:12
【问题描述】:

我正在使用 python 中提供的cmis 包从 FileNet 存储库下载文档。我正在使用包中提供的 getcontentstream 方法。但是,它会返回带有“Pk”并以“PK”结尾的内容文件。当我用谷歌搜索时,我知道它是 excel zip 包内容。有没有办法将内容保存到excel文件中。我应该能够打开下载的excel。我正在使用下面的代码。但是需要获取字节对象而不是 str。我注意到结果类型是string.io

# expport the result
result = testDoc.getContentStream()
outfile = open(sample.xlsx, 'wb')
outfile.write(result.read())
result.close()
outfile.close()

【问题讨论】:

  • 也许.encode("latin-1") 的输出得到一个字节对象?
  • 使用zipfile包解压文件/流 -> docs.python.org/3/library/zipfile.html
  • Python 在其标准库中没有提供用于读写 Excel .xlsx 格式文件的模块,因此您可能需要从第三方找到并安装一个模块(或编写你自己的代码来做)。
  • @Wouterr。谢谢您的答复。有效。我用 latin-1 编码并将字符串转换为字节,我成功地打开了 excel 文件,没有任何问题。我的代码工作代码如下。 result = testDoc.getContentStream() outfile = open(sample.xlsx, 'wb') outfile.write(result.read().encode('latin-1')) result.close() outfile.close()跨度>
  • @Bitonator。感谢您查看我的问题和您的回复。欣赏它

标签: python cmis


【解决方案1】:

您好,欢迎来到 stackoverflow。我注意到你的帖子有几点。

直接回答您收到的错误代码。您将输出文件 FileStream 称为二进制,但是 result.read() 必须采用 Unicode 字符串格式,这就是您收到此错误的原因。您可以尝试在将其传递给 outfile.write() 函数之前对其进行编码(例如:outfile.write(result.read().encode()))。

您也可以直接通过以下方式编写 Unicode:

result = testDoc.getContentStream()
result_text = result.read()

from zipfile import ZipFile

with ZipFile(filepath, 'w') as zf:
    zf.writestr('filename_that_is_zipped', result_text)

不是我不确定您的 ContentStream 中有什么,但请注意,一个 excel 文件是由压缩的 xml 文件组成的。 excel文件所需的最小文件结构如下:

  • _rels/.rels 包含 excel 架构
  • docProps/app.xml 包含工作表数量和工作表名称
  • docProps/core.xml 样板用户信息和创建日期
  • xl/workbook.xml 包含工作簿链接的工作表名称 rdId
  • xl/worksheets/sheet1.xml(以及此文件夹中的更多工作表)包含每个工作表的单元格数据
  • xl/_rels/workbook.xml.rels 包含 zipfile 中的工作表文件位置
  • xl/sharedStrings.xml 如果您只有字符串单元格值
  • [Content_Types].xml将架构应用于文件类型

我最近从头开始拼凑一个excel文件,如果你想看代码,请查看https://github.com/PydPiper/pylightxl

【讨论】:

  • 感谢您的回复。有效。我用 latin-1 编码并将字符串转换为字节,我成功地打开了 excel 文件,没有任何问题。我的代码工作代码如下。 result = testDoc.getContentStream() outfile = open(sample.xlsx, 'wb') outfile.write(result.read().encode('latin-1')) result.close() outfile.close()跨度>
猜你喜欢
  • 1970-01-01
  • 2018-03-11
  • 2016-04-07
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 2019-06-03
相关资源
最近更新 更多