用python复制粘贴excel指定单元格(可保留格式) 您所在的位置:网站首页 如何用excel编程 用python复制粘贴excel指定单元格(可保留格式)

用python复制粘贴excel指定单元格(可保留格式)

2023-06-16 01:42| 来源: 网络整理| 查看: 265

近期学习了openpyxl的用法,发现居然没有【复制、粘贴】这么基础的函数。而且若要用python带格式复制粘贴指定区域的单元格,参考资料更少。

于是参考各路大佬的笔记,整合如下。

本代码只完成一次复制粘贴,各位可根据自己的需要加以利用,比如:可搭配遍历文件等实现多个excel中指定区域的复制,并汇总于指定区域的内容。

# 复制区域cell、带格式粘贴: 比如把a1:f16带格式复制粘贴到h23:m38 #导入包 import openpyxl import copy #path单引号内放入指定要操作的excel的路径 (本文举例的复制与粘贴,位于同一excel的同一sheet) path = r'E:\OneDrive\Python_Note\Excel操作\03\反馈表-小寨支行.xlsx' wb = openpyxl.load_workbook(path) ws = wb.active #本行代码意思是指定ws为当前在excel中处于选中状态的sheet为ws。 #若excel内有多个sheet,建议使用ws=wb['sheet的名字'] #以字符串输入复制、粘贴的区域,如'a1:f16','h23:m38'(必须大小一致) Source_Area = 'a1:f16' Target_Area = 'h23:m38' #分别指定复制和粘贴所在sheet的位置(本文复制粘贴的单元格区域都在ws内,ws是什么在上面已经指定好) source_area = ws[Source_Area] target_area = ws[Target_Area] #创造source_cell_list,用以和target_cell_list一一对应: source_cell_list = [] for source_row in source_area: for source_cell in source_row: sc_str = str(source_cell) point_time = sc_str.count('.') sc_str = sc_str.replace('.', '', point_time - 1) start = sc_str.find('.') sc_str = sc_str[start+1 : -1] source_cell_list.append(sc_str) #提取出单元格编号的字符串,如'C8' print('source_cell_list:',source_cell_list) target_cell_list = [] for target_row in target_area: for target_cell in target_row: tc_str = str(target_cell) point_time = tc_str.count('.') tc_str = tc_str.replace('.', '', point_time - 1) start = tc_str.find('.') tc_str = tc_str[start + 1: -1] target_cell_list.append(tc_str) # 提取出单元格编号的字符串,如'L10' print('target_cell_list:',target_cell_list) #获取要复制的单元格总个数: cells = len(source_cell_list) #提取并复制格式: i=0 while i


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有