openpyxl 带格式复制单元格,有一些bug,暂时搞不明白

import openpyxl
from openpyxl.styles import Font, colors, Alignment
from openpyxl.utils import get_column_letter, column_index_from_string
from copy import copy # 浅拷贝

def info(obj,flag=True):
    for i in dir(obj):
        if flag:
            if not i.startswith('_'):
                print(i)
        else:
            print(i)
    exit()

source_path = r'c:/users/administrator/desktop/bill.xlsx'
source_workbook = openpyxl.load_workbook(source_path)
source_sheet = source_workbook['空表']

target_workbook = openpyxl.Workbook()
target_sheet = target_workbook.active

nrows = 38 #source_sheet.max_row
ncols = 24 #source_sheet.max_column

for it in source_sheet.merged_cells:
    target_sheet.merge_cells(it.coord)

for r in range(1,nrows+1):
    target_sheet.row_dimensions[r].height = source_sheet.row_dimensions[r].height
    for c in range(1,ncols+1):
        if r == 1:
            column_letter = get_column_letter(c)
            column_width = source_sheet.column_dimensions[column_letter].width
            target_sheet.column_dimensions[column_letter].width = column_width
            print(column_letter+str(r),column_width)
            # 这个获取宽度的方法,返回的值不准确,
            
        source_cell = source_sheet.cell(row = r, column = c)
        target_cell = target_sheet.cell(row = r, column = c)
        
        target_sheet.cell(row = r, column = c, value = source_cell.value)
        target_cell.fill = copy(source_cell.fill)
        
        if source_cell.has_style:
            target_cell._style = copy(source_cell._style)
            target_cell.font = copy(source_cell.font)
            target_cell.border = copy(source_cell.border)
            target_cell.fill = copy(source_cell.fill)
            target_cell.number_format = copy(source_cell.number_format)
            target_cell.protection = copy(source_cell.protection)
            target_cell.alignment = copy(source_cell.alignment)
            
        if source_cell.hyperlink:
            target_cell.hyperlink = copy(source_cell.hyperlink)
            
        if source_cell.comment:
            target_cell.comment = copy(source_cell.comment)

target_workbook.save(r'c:/users/administrator/desktop/demo3.xlsx')
        

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值