2
votes

Not only am i fairly new to python, but this is my first post on this forum. I am learning how to integrate python and excel. I was able to get the following code:

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()

to work on Jupyter Notebook and through the anaconda python shell, however when i run in Spyder, i get the following error message on the ipython console:

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'

I look forward to all your help.

1
Always try googleing the error. First result here searching AttributeError: 'Workbook' object has no attribute 'add_sheet' on google.gobrewers14
This question has nothing to do with either anaconda, jupyter-notebook, nor spyder, so please don't tag it as such. Also, please come up with a better title. Your title should not be a request, it should be a short description of the problem. I'll go ahead and change it to something sensible. Note, this is not a "forum" but a Question and Answer site.juanpa.arrivillaga
Er, your code doesn't seem to match your error message. Your code says ws_1 = wb.add_worksheet('first_sheet') but the error message says ws_1 = wb.add_sheet('first_sheet'). Could you check to see whether that's accurate?DSM
yes the code should read wb.add_sheet('first_sheet'). i am editing the original post as well.Rsaha

1 Answers

2
votes

The method name in xlsxwriter, as shown in the xlsxwriter documentation, is add_worksheet. You're using add_sheet. I suspect you may have read examples from xlwt or a different library, because in xlwt you'd have

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

but with xlsxwriter you have

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