本期,我们利用xlwings拆分Excel,将Excel中某列相同的类别分别拆成一个个单独的Excel文件,以下面的Excel文件为例:
将里面的“姓名”列拆出来,变成单独的Excel文件,具体代码为:
import xlwings as xwimport ospath=r'C:\Users\XXX\Python_project\Python办公自动化\xlwings对Excel进行拆分\Combine.xlsx'des_path=r'C:\Users\XXX\Python_project\Python办公自动化\xlwings对Excel进行拆分\\'app = xw.App(visible=False, add_book=False)workbook = app.books.open(path)worksheet = workbook.sheets['combine']header = worksheet['A1:F1'].valuedata1 = worksheet.range('A2').expand().valuedata2 = dict()for i in range(len(data1)): name = data1[i][1] if name not in data2: data2[name] = [] data2[name].append(data1[i])for k, v in data2.items(): nw = xw.Book() nws = nw.sheets.add(k) nws['A1'].value = header nws['A2'].value = v nws.autofit() nw.save(des_path + f'{k}.xlsx') nw.close()app.quit()
运行结果为:
每一个姓名都单独成为了一个Excel,内容如下:
自己动手试试吧