复制原始excel,包括格式和批注
从第一行第一列开始;
from openpyxl import load_workbook,Workbook
from copy import copy
if __name__ == '__main__':
excel_path = '测试数据.xlsx'
path1 = 'D:/2.xlsx'
wb = load_workbook(excel_path) # 打开待操作的表
sheet = wb.active
new_wb = Workbook() # 新建一个表
new_sheet = new_wb.create_sheet('Sheet_new') #新建一个new_sheet
num=1 #从第一行到第n行
for row in sheet.values:
for i, content in enumerate(row):
cell = sheet.cell(num,i+1)
new_cell = new_sheet.cell(num,i+1) #从第1行第1列开始
new_cell.value = content
new_cell.font = copy(cell.font) #复制单元格格式
new_cell.fill = copy(cell.fill) #复制单元格颜色
if cell.comment:
new_cell.comment = cell.comment #有批注的复制批注
num=num+1 #换行,手动设置行数+1
new_wb.save(path1) # 写入完成,保存工作簿