为什么xlwings分拆excel表格提示AttributeError: 'float' object has no attribute 'lower'
这要怎么解决
import xlwings as xw
import pandas as pd
app=xw.App(visible=True,add_book=False)
wb=app.books.open('C:\\Users\\Link\\Desktop\\python数据分析期末报告\\xiugai.xlsx')
data_pd=pd.DataFrame()
for i in wb.sheets:
data1=i.range('C1').options(pd.DataFrame,header=1,index=False,expand='table').value
if '交易日期' in data1:
data_pd=data_pd.append(data1)
data_new=data_pd.groupby('交易日期')
new_wb=app.books.add()
for n,group in data_new:
new_sht=new_wb.sheets.add(n)
new_sht.range('D:D').api.NumberFormat='#,##0.00'
new_sht.range('A1').options(index=False).value=group
new_sht.autofit()
new_wb.save('C:\\Users\\Link\\Desktop\\python数据分析期末报告\\aaa.xlsx')
new_wb.close()
wb.close()
app.quit()
AttributeError Traceback (most recent call last)
Input In [11], in <cell line: 13>()
12 new_wb=app.books.add()
13 for n,group in data_new:
---> 14 new_sht=new_wb.sheets.add(n)
15 new_sht.range('D:D').api.NumberFormat='#,##0.00'
16 new_sht.range('A1').options(index=False).value=group
File E:\Anaconda3\lib\site-packages\xlwings\main.py:4337, in Sheets.add(self, name, before, after)
4320 """
4321 Creates a new Sheet and makes it the active sheet.
4322
(...)
4334
4335 """
4336 if name is not None:
-> 4337 if name.lower() in (s.name.lower() for s in self):
4338 raise ValueError("Sheet named '%s' already present in workbook" % name)
4339 if before is not None and not isinstance(before, Sheet):
AttributeError: 'float' object has no attribute 'lower'
这是我的excel表
这要怎么解决
望采纳
这个错误是由于你使用的循环变量 n 不是一个字符串,而是一个 float 类型的数字。在 xlwings 中,add 函数的第一个参数必须是字符串,代表新工作表的名称。
如果你想使用循环变量 n 作为新工作表的名称,则需要将其转换为字符串。你可以使用 Python 内置函数 str 将 n 转换为字符串,然后再传入 add 函数即可。
你可以将代码中的
new_sht=new_wb.sheets.add(n)
修改为
new_sht=new_wb.sheets.add(str(n))