我不仅对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')回溯(最近一次呼叫最后一次):
文件"",第1行,in runfile(' C:/Users/Python/excel_integration1.py' ;, wdir =' C:/ Users / Python')
文件 " C:\用户\ Anaconda2 \ lib中\站点包\ spyder的\ utils的\站点\ sitecustomize.py&#34 ;, 第866行,在runfile中 execfile(filename,namespace)
文件 " C:\用户\ Anaconda2 \ lib中\站点包\ spyder的\ utils的\站点\ sitecustomize.py&#34 ;, 第87行,在execfile中 exec(compile(scripttext,filename,' exec'),glob,loc)
File" C:/Users/Python/excel_integration1.py" ;,第7行,在 ws_1 = wb.add_sheet(' first_sheet')
属性错误:'工作簿'对象没有属性' add_sheet'
我期待着你的帮助。
答案 0 :(得分:2)
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>