pandas “Workbook”对象没有属性“write”

niwlg2el  于 2023-10-14  发布在  其他
关注(0)|答案(1)|浏览(193)

我计划在每次调用以下函数后,在最后一张表和平均数据对应的行中保存当月的平均数据(每个月在Excel文件中单独一张表)。
例如:在每个月的第一栏和第二行(每张)写着“运费”,全年平均为340美元。代码应将此值存储在最后一个工作表的第一列和第二行中。我写的函数如下:

def mean_cal(year_num):
    file = f'year_data/year-{year_num}.xlsx'
    dataframe = pd.read_excel(f'year_data/year-{year_num}.xlsx',
                              sheet_name=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', 'total'])
    
    month = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
    categor = ['incomes', 'costs']
    info = []
    total = 0
    exl = xw.Workbook(file)
    for categ in categor:
        for row in range(0, 19):
            for month_check in month:
                try:
                    info.append(dataframe[month_check][categ][row])
                except ValueError or KeyError:
                    continue

            for collector in info:
                total += collector

            if categ == 'incomes':
                exl.write(f'F{row}', (total / (len(info))))
            else:
                pass

但它给出的错误:

Traceback (most recent call last):
  File "D:\Mahdi\Programming\Projects\Rabin amc\proj_func.py", line 209, in <module>
    mean_cal(1402)
  File "D:\Mahdi\Programming\Projects\Rabin amc\proj_func.py", line 106, in mean_cal
    exl.write(f'F{row}', (total / (len(info))))
    ^^^^^^^^^
AttributeError: 'Workbook' object has no attribute 'write'```
r9f1avp5

r9f1avp51#

变量exl被赋给一个Workbook对象。然而,正如错误消息所说,这种类型的对象没有write()属性。
在将值写入单元格之前,必须创建一个Worksheet对象。这个对象有一个write()属性。
从xlsxwriter文档复制的简单用法示例:

workbook   = xlsxwriter.Workbook('filename.xlsx')

worksheet1 = workbook.add_worksheet()
worksheet2 = workbook.add_worksheet()

worksheet1.write('A1', 123)

workbook.close()

值得注意的是,除了以字符串形式提供单元地址之外,还可以将其作为行索引整数和列索引整数提供。再次从xlsxwriter文档复制的示例:

# These are equivalent.
worksheet.write(0, 0, 'Hello')
worksheet.write('A1', 'Hello')

相关问题