close()问题求助
本帖最后由 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
file_list = eg.fileopenbox(multiple=True)
for i in file_list:
workbook2 = app.books.open(i)
worksheet2 = workbook2.sheets
worksheet2.copy(after=worksheet1)
workbook2.close()
worksheet1.delete()
workbook1 = eg.filesavebox(default='*.xlsx')
workbook1.close()
app.quit()
参考https://blog.csdn.net/qq_35462323/article/details/82353299,有帮助给个最佳 workbook1 = eg.filesavebox(default='*.xlsx')
读取的是一个字符串而不是文件对象,不能close() 豆嘉木 发表于 2023-1-6 17:50
参考https://blog.csdn.net/qq_35462323/article/details/82353299,有帮助给个最佳
不行啊,在workbook1.close()前加一行又提示加这一行报错,还是报同样的错误 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
file_list = eg.fileopenbox(multiple=True)
for i in file_list:
workbook2 = app.books.open(i)
worksheet2 = workbook2.sheets
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()
页:
[1]