gpt4 book ai didi

Python to excel、openpyxl 和文件格式无效

转载 作者:行者123 更新时间:2023-11-28 17:26:52 25 4
gpt4 key购买 nike

以下是一个简单的片段,用于打开一个 .xlsm 文件,用 python 向其中写入一些值,然后保存。

import openpyxl
from openpyxl import load_workbook

def toExcel():
wb = load_workbook(filename="C:\\Users\\Mark\\Documents\\Test.xlsm")
ws = wb.worksheets[0]
ws.cell(row=1, column=1).value = 'foo'
ws['A2'] = 'bar'
wb.save("C:\\Users\\Mark\\Documents\\Test1.xlsm")

toExcel()

当文件打开和保存时,它提到文件格式无效/损坏并且无法打开。如果从 wb.save 中删除 .xlsm,它将在选择 excel with Open With 后保存并打开。为什么文件格式无效?

最佳答案

来自这里:https://openpyxl.readthedocs.io/en/default/tutorial.html#saving-to-a-file

Note

The following will fail:

>>> wb = load_workbook('document.xlsx')
>>> # Need to save with the extension *.xlsx
>>> wb.save('new_document.xlsm')
>>> # MS Excel can't open the document
>>>
>>> # or
>>>
>>> # Need specify attribute keep_vba=True
>>> wb = load_workbook('document.xlsm')
>>> wb.save('new_document.xlsm')
>>> # MS Excel can't open the document
>>>
>>> # or
>>>
>>> wb = load_workbook('document.xltm', keep_vba=True)
>>> # If us need template document, then we need specify extension as *.xltm.
>>> # If us need document, then we need specify attribute as_template=False.
>>> wb.save('new_document.xlsm', as_template=True)
>>> # MS Excel can't open the document

关于Python to excel、openpyxl 和文件格式无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38173861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com