Python办公自动化应用(三)

  • 应用说明

根据中、英文对照字典(参见Python办公自动化应用(一))将Excel表单元格里的中文替换为英文。

  • 工具函数
#定义打印区域
def print_area(sheetname):
    
    if sheetname.startswith("11-"):
        return "B2:M36"
  
    if sheetname.startswith("12-"):
        return "B2:X37"

    if sheetname.startswith("13-"):
        return "B2:X37"

    if sheetname.startswith("14-"):
        return "B2:Y37"


#设置样式,自动换行,具中显示,控制列宽
def set_style(file):
    wb = load_workbook(file)
    col_start=ord('A')
    col_end=ord('Z')
    for ws in wb:
        #设置列宽
        set_column(ws)
        #设置页边距
        ws.page_margins = PageMargins(
            left=0.31,  # 左边距
            right=0.31,  # 右边距
            top=0.35,  # 上边距
            bottom=0.35,  # 下边距
            header=0.19,  # 页眉边距
            footer=0.31  # 页脚边距
        )
        for row_index in range(40):

            if row_index>=3 and row_index<=6:
                #设置固定行高
                ws.row_dimensions[row_index].height=30
            if row_index>=21 and row_index<=34:
                #判断是否空行,是则跳过,否则设置固定行高
                if not row_empty(ws,row_index):
                    #设置固定行高
                    ws.row_dimensions[row_index].height=30
                #设置空行行高
                # else:
                #     ws.row_dimensions[row_index].height=6
            for col_index in range(col_start,col_end+1):
                cell_name = str(chr(col_index)) + str(row_index + 1)
                if ws[cell_name].value != None:
                    ws[cell_name].alignment = Alignment(wrapText=True,horizontal='center',vertical='center')
    wb.save(file)
  • 业务代码实现
from openpyxl import load_workbook
import utils


def load_mapping(mapping_file):
    mapping = {}
    try:
        # 加载映射文件
        wb = load_workbook(mapping_file)
        sheet = wb.active
        for row in sheet.iter_rows(min_row=2,values_only=True):
            if row[0] and row[2]:
                # 将中文作为键,英文作为值存入字典
                mapping[row[0]] = row[2]
    except FileNotFoundError:
        print(f"错误:未找到映射文件 {mapping_file}")
    return mapping


def replace_chinese_to_thai(input_file, output_file, mapping_file):
    # 加载映射表
    mapping = load_mapping(mapping_file)
    if not mapping:
        return

    try:
        # 加载要替换的 Excel 文件
        wb = load_workbook(input_file)
        for sheet in wb:
            #设置纸张方向横向
            sheet.page_setup.orientation=sheet.ORIENTATION_LANDSCAPE
            sheet.print_area=utils.print_area(sheet.title)
            for row in sheet.iter_rows():
                for cell in row:
                    if cell.value in mapping:
                        # 如果单元格的值在映射表中,将其替换为对应的英文
                        cell.value = mapping[cell.value]
        # 保存替换后输出的 Excel 文件
        wb.save(output_file)
        #设置样式,自动换行,居中显示
        utils.set_style(output_file)
        print(f"已将 {input_file} 中的中文替换为英文,并保存到 {output_file}")
    except FileNotFoundError:
        print(f"错误:未找到输入文件 {input_file}")



if __name__ == "__main__":
    # 中文原始文件夹
    input_dict = r'D:\Chinese'
    # 英文输出文件夹
    output_dict = r'D:\English'
    # 中英文对照字典
    mapping_file = r'D:\translateZ.xlsx'

    for file in utils.get_file_names(input_dict):
        output_file = utils.translate_to_thai(output_dict, file)
        replace_chinese_to_thai(file, output_file, mapping_file)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值