使用xlsxwri中的工作簿对象时,工作簿对象没有“添加工作表”属性

2024-04-26 01:01:31 发布

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

我不仅对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笔记本和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'

我期待你的帮助。


Tags: inpyimportadddatawslinesite
1条回答
网友
1楼 · 发布于 2024-04-26 01:01:31

如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>

相关问题 更多 >