Skip to main content
 首页 » 编程设计

python之使用 xlsxwriter 中的工作簿对象时,工作簿对象没有属性 'add_sheet'

2024年10月01日7dyllove98

不仅我对 python 还很陌生,而且这是我在这个论坛上的第一篇帖子。我正在学习如何集成 python 和 excel。我能够得到以下代码:

import numpy as np 
import pandas as pd 
import xlrd, xlwt 
import xlsxwriter 
path = "C:/Users/Python/data/" 
data = np.arange(1, 101).reshape((10,10)) 
wb = xlsxwriter.Workbook(path + 'workbook.xlsx') 
ws_1 = wb.add_sheet('first_sheet') 
ws_2 = wb.add_sheet('second_sheet') 
for c in range(data.shape[0]): 
    for r in range(data.shape[1]): 
        ws_1.write(r, c, data[c, r]) 
        ws_2.write(r, c, data[c, r]) 
wb.close() 

在 Jupyter Notebook 上工作并通过 anaconda python shell,但是当我在 Spyder 中运行时,我在 ipython 控制台上收到以下错误消息:

runfile('C:/Users/Python/excel_integration1.py', wdir='C:/Users/Python') Traceback (most recent call last):

File "", line 1, in runfile('C:/Users/Python/excel_integration1.py', wdir='C:/Users/Python')

File "C:\Users\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile execfile(filename, namespace)

File "C:\Users\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc)

File "C:/Users/Python/excel_integration1.py", line 7, in ws_1 = wb.add_sheet('first_sheet')

AttributeError: 'Workbook' object has no attribute 'add_sheet'

我期待着您的所有帮助。

请您参考如下方法:

如 xlsxwriter 文档中所示,xlsxwriter 中的方法名称是 add_worksheet。您正在使用 add_sheet。我怀疑您可能已经阅读过 xlwt 或其他库中的示例,因为在 xlwt 中您会有

>>> import xlwt 
>>> wb = xlwt.Workbook() 
>>> wb.add_sheet("some name") 
<xlwt.Worksheet.Worksheet object at 0x7f6633b466d8> 

但是有了 xlsxwriter 你就有了

>>> import xlsxwriter 
>>> wb = xlsxwriter.Workbook() 
>>> wb.add_sheet("won't work") 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'Workbook' object has no attribute 'add_sheet' 
>>> wb.add_worksheet("will work") 
<xlsxwriter.worksheet.Worksheet object at 0x7f6632e70320>