首页 文章

使用xlsxwriter中的Workbook对象时,Workbook对象没有属性'add_sheet'

提问于
浏览
1

我不仅对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(最近一次调用最后一次):文件“”,第1行,在runfile中('C:/ Users /Python/excel_integration1.py',wdir ='C:/ Users / Python')文件“C:\ Users \ Anaconda2 \ lib \ site-packages \ spyder \ utils \ site \ sitecustomize.py”,第866行,在runfile中execfile(filename,namespace)文件“C:\ Users \ Anaconda2 \ lib \ site-packages \ spyder \ utils \ site \ sitecustomize.py”,第87行,在execfile exec中(compile(scripttext,filename,'exec'), glob,loc)文件“C:/Users/Python/excel_integration1.py”,第7行,在ws_1 = wb.add_sheet('first_sheet')中AttributeError:'Workbook'对象没有属性'add_sheet'

我期待着你的帮助 .

1 回答

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

相关问题