通過openpyxl庫來處理xlsx中互相復(fù)制工作表的工作玩敏。
代碼中僅能處理指定名稱的xlsx中的某一個(gè)工作表,稍加修改便能指定是第幾個(gè)工作表。
源碼如下:
from openpyxl.worksheet.worksheet import Worksheet
from openpyxl import Workbook, load_workbook
from copy import copy
from openpyxl.utils import get_column_letter
def xlsx_sheet_copy(src_path, tag_path, sheet_name): # 跨xlsx復(fù)制sheet
# 跨xlsx文件復(fù)制源文件xlsx中指定的sheet
# 保留所有格式,以及行高列寬焕梅,視覺效果幾乎一致
# 不能復(fù)制除了文字以外的東西,例如圖片
# src_path:源xlsx文件路徑
# tag_path:目標(biāo)xlsx文件路徑
# sheet_name:需要復(fù)制的源xlsx文件sheet的名稱
src_workbook = load_workbook(src_path) # 打開源xlsx
src_file_sheet = src_workbook[sheet_name] # 打開目標(biāo)sheet
tag_workbook = load_workbook(tag_path) # 打開目標(biāo)xlsx
tag_file_sheet = tag_workbook.create_sheet(sheet_name) # 新建一個(gè)同名空sheet等待寫入
for row in src_file_sheet:
# 遍歷源xlsx文件制定sheet中的所有單元格
for cell in row: # 復(fù)制數(shù)據(jù)
tag_file_sheet[cell.coordinate].value = cell.value
if cell.has_style: # 復(fù)制樣式
tag_file_sheet[cell.coordinate].font = copy(cell.font)
tag_file_sheet[cell.coordinate].border = copy(cell.border)
tag_file_sheet[cell.coordinate].fill = copy(cell.fill)
tag_file_sheet[cell.coordinate].number_format = copy(
cell.number_format
)
tag_file_sheet[cell.coordinate].protection = copy(cell.protection)
tag_file_sheet[cell.coordinate].alignment = copy(cell.alignment)
wm = list(zip(src_file_sheet.merged_cells)) # 開始處理合并單元格
if len(wm) > 0: # 檢測源xlsx中合并的單元格
for i in range(0, len(wm)):
cell2 = (
str(wm[i]).replace("(<MergedCellRange ", "").replace(">,)", "")
) # 獲取合并單元格的范圍
tag_file_sheet.merge_cells(cell2) # 合并單元格
# 開始處理行高列寬
for i in range(1, src_file_sheet.max_row + 1):
tag_file_sheet.row_dimensions[i].height = src_file_sheet.row_dimensions[
i
].height
for i in range(1, src_file_sheet.max_column + 1):
tag_file_sheet.column_dimensions[
get_column_letter(i)
].width = src_file_sheet.column_dimensions[get_column_letter(i)].width
tag_workbook.save(tag_path) # 保存
tag_workbook.close() # 關(guān)閉文件
src_workbook.close()