import copy
import openpyxl
from openpyxl.utils import get_column_letter
import glob
class Cpxx():
write_path="./xx.xlsx"
write_wb=None
def __init__(self):
root_path="./"
xlsx1_path=glob.glob("./1/*.xlsx")
xlsx2_path=glob.glob("./2/*.xlsx")
self.write_wb=openpyxl.Workbook()
for i in xlsx1_path:
now_data=self.read_xlsx(i)
self.write_xlsx(now_data)
for j in xlsx2_path:
now_data=self.read_xlsx(j)
self.write_xlsx(now_data)
self.write_wb.save(self.write_path)
def read_xlsx(self,path):
# 读取xlsx文件
workbook = openpyxl.load_workbook(path)
sheet = workbook.get_sheet_names()
return workbook.get_sheet_by_name(sheet[0])
def write_xlsx(self,sheet):
now_sheet=self.write_wb.create_sheet(sheet.title)
now_sheet.sheet_properties.tabColor = sheet.sheet_properties.tabColor
# 开始处理合并单元格形式为“(<CellRange A1:A4>,),替换掉(<CellRange 和 >,)' 找到合并单元格
wm = list(sheet.merged_cells)
if len(wm) > 0:
for i in range(0, len(wm)):
cell2 = str(wm[i]).replace('(<CellRange ', '').replace('>,)', '')
now_sheet.merge_cells(cell2)
for i, row in enumerate(sheet.iter_rows()):
now_sheet.row_dimensions[i+1].height = sheet.row_dimensions[i+1].height
for j, cell in enumerate(row):
now_sheet.column_dimensions[get_column_letter(j+1)].width = sheet.column_dimensions[get_column_letter(j+1)].width
now_sheet.cell(row=i + 1, column=j + 1, value=cell.value)
# 设置单元格格式
source_cell = sheet.cell(i+1, j+1)
target_cell = now_sheet.cell(i+1, j+1)
target_cell.fill = copy.copy(source_cell.fill)
if source_cell.has_style:
target_cell._style = copy.copy(source_cell._style)
target_cell.font = copy.copy(source_cell.font)
target_cell.border = copy.copy(source_cell.border)
target_cell.fill = copy.copy(source_cell.fill)
target_cell.number_format = copy.copy(source_cell.number_format)
target_cell.protection = copy.copy(source_cell.protection)
target_cell.alignment = copy.copy(source_cell.alignment)
if __name__=="__main__":
Cpxx()
openpyxl 跨文件复制sheet
最新推荐文章于 2024-05-09 10:51:23 发布