python 3 | docx的读写 | excel的读 | word行中添加新的key-value

python 3| docx的读写

杂活程序3
在docx文件中,有许多固定格式内容,在制定位置添加制定数据信息,在key2后添加一组key-value

姊妹篇

python 3| docx的读写 | excel的读 | word行中添加新的key-value - 我是一块小石头 - CSDN博客
https://blog.csdn.net/stone_fall/article/details/96428915
python 3 | doc转docx - 我是一块小石头 - CSDN博客
https://blog.csdn.net/stone_fall/article/details/96428876
Python 3 | txt转Excel | 用拼音+数字对各个数据元编码 | 读取多个文件夹内容 | import xlwt + xpinyin + os - 我是一块小石头 - CSDN博客
https://blog.csdn.net/stone_fall/article/details/96428734

数据格式

4.1 xxxxx
key1:value
key2:。。
key3:。
key4:。
key5:。
key6:。
key7:。
key8:。
key9:。
key10:。

key1:value
key2:。。
key3:。
key4:。
key5:。
key6:。
key7:。
key8:。
key9:。
key10:。

……

import docx
import xlrd

代码

        docx_path = os.path.join(docx_dir_path,docx_name)
        excel_dir_path = os.path.join(excel_original_data_path, docx_dirs)
    	final_dir_path = os.path.join(final_data_path,docx_dirs)
        # 获取docx文件
        file = docx.Document(docx_path)
        # 获取excel文件
        excel = xlrd.open_workbook(excel_path)
        # 获取sheet
        sheet = excel.sheet_by_index(0)
        # 创建字典
        myDict = dict()
        for i in range(sheet.nrows):
            if i == 0:
                continue
            # print(sheet.row_values(i))
            myDict[sheet.cell(i, 0).value] = sheet.cell(i, 2).value
        print(myDict)
        # 制定位置添加word行
        # 几个标识key
        key = '中文名称'
        key_1 = '版本'
        key_2 = '非中文标识'

        for para in file.paragraphs:
            para_single = para.text.strip('\n')
            para_single = para_single.strip()
            if len(para_single) == 0:
                continue
            para_single = para_single.split(':', 1)
            if para_single[0] == key:
                value = ''.join(para_single[1:])
                # print(value)
                # print(myDict[value])
                str1 = key_2 + ':'
                str2 = myDict[value]
            if para_single[0] == key_1:
                #     # para.insert_paragraph_before(str)
                run1 = para.insert_paragraph_before()
                run1.add_run(str1).bold = True
                run1.add_run(str2)

        file.save(final_path)
发布了134 篇原创文章 · 获赞 57 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/stone_fall/article/details/96428915
今日推荐