openpyxl使用注意事项

使用openpyxl修改已经存在的excel时,记得要将 wb = op.load_workbook() 与 wb.save() 放在一个循环下,不然会出现文件已修改却保存不了的状况

总有人喜欢更改sheet名称,这个时候就可以用ws = wb.worksheets[index]根据索引号来选择工作表,其他的选择工作表的方法有:ws = wb.active , ws = wb['sheetName']

下面是合并单元格的代码:

import openpyxl as op


folder_path2 = r'文件夹路径'
path1 = folder_path2 + '\\' + '11.xlsx'
path2 = folder_path2 + '\\' + '22.xlsx'
wb = op.load_workbook(path1)
ws = wb['Sheet1']
wb1 = op.load_workbook(path2)
ws1 = wb1['Sheet2']
merge = ws.merged_cells
for i in merge:
    ws1.merge_cells(str(i))
wb1.save(path2)

你可能感兴趣的:(python,python)