马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 zxcv1100 于 2023-1-6 17:26 编辑
把多个excel文件合并到一个文件中,报错:
AttributeError: 'str' object has no attribute 'close' ,请大神帮忙看看
代码如下:
import xlwings as xw
import easygui as eg
app = xw.App(visible=True, add_book=False)
workbook1 = app.books.add()
worksheet1 = workbook1.sheets[0]
file_list = eg.fileopenbox(multiple=True)
for i in file_list:
workbook2 = app.books.open(i)
worksheet2 = workbook2.sheets[0]
worksheet2.copy(after=worksheet1)
workbook2.close()
worksheet1.delete()
workbook1 = eg.filesavebox(default='*.xlsx')
workbook1.close()
app.quit()
eg.filesavebox 返回的是一个路径,类型为字符串,字符串是没有 close 方法的,
对你的代码修改如下:
import xlwings as xw
import easygui as eg
app = xw.App(visible=True, add_book=False)
workbook1 = app.books.add()
worksheet1 = workbook1.sheets[0]
file_list = eg.fileopenbox(multiple=True)
for i in file_list:
workbook2 = app.books.open(i)
worksheet2 = workbook2.sheets[0]
worksheet2.copy(after=worksheet1)
workbook2.close()
worksheet1.delete()
savepath = eg.filesavebox(default='*.xlsx') # 改了这里,不要覆盖掉前面的 workbook1,用另一个变量保存路径
workbook1.save(savepath if savepath.endswith('.xlsx') else f'{savepath}.xlsx') # 添加了这一行保存,因为文件名不以表格的扩展名结尾会出错,所以做了一个判断
workbook1.close()
app.quit()
|