无法写入 excel AttributeError:“工作表”对象没有属性“写入”

Posted

技术标签:

【中文标题】无法写入 excel AttributeError:“工作表”对象没有属性“写入”【英文标题】:Cannot write to an excel AttributeError: 'Worksheet' object has no attribute 'write' 【发布时间】:2018-05-26 23:31:46 【问题描述】:

我正在尝试将文本写入 Excel,我正在关注此 post。这在早些时候工作,但现在不是。我明白了:

错误:

line 122, in <module>
    worksheet.write(0, 11, 'HI')
AttributeError: 'Worksheet' object has no attribute 'write'

df1

A  E
c  d
c  D

代码:

writer = pd.ExcelWriter("C:\\33.xlsx")
df1.to_excel(writer, startrow=0, startcol=0, index = False)

worksheet = writer.sheets['Sheet1']
worksheet.write(0, 11, 'YO')
worksheet.write(1, 11, 'HI')

我也试过了:

import xlrd
import xlwt
from xlutils.copy import copy
import os.path
rb = xlrd.open_workbook('C:\\13.xlsx',formatting_info=True)
r_sheet = rb.sheet_by_index(0) 
wb = copy(rb) 
sheet = wb.get_sheet(0) 
sheet.write(5,2,"string")
wb.save('C:\\13.xlsx')

我明白了:

    with open(filename, "rb") as f:
OSError: [Errno 22] Invalid argument: 'C:\\13.xlsx"'

如何修复AttributeError: 'Worksheet' object has no attribute 'write'

【问题讨论】:

【参考方案1】:

给出的原因:AttributeError: 'Worksheet' object has no attribute 'write'

是因为我意识到我没有在这台电脑上安装 xlsxwriter。

pip install xlsxwriter

现在可以了。

【讨论】:

如果您明确想要使用 XlsxWriter,那么您应该将 engine='xlsxwriter' 添加到 pd.ExcelWriter() 否则 Pandas 可以替换 OpenPyXL(如果可用而 XlsxWriter 不可用)。因此缺少方法错误。如果您没有使用 XlsxWriter 特定的方法,那么使用哪个引擎并不重要。

以上是关于无法写入 excel AttributeError:“工作表”对象没有属性“写入”的主要内容,如果未能解决你的问题,请参考以下文章