在使用Python更改.docx文件中表格中的字母颜色时,可以使用以下方法:

huangapple go评论69阅读模式
英文:

Changing letter color in a table within a .docx file using Python

问题

如果有人有使用**python-docx**库或任何替代方法来完成此任务的经验,我将非常感激您的指导。具体来说,我想知道如何在保持表格中其余文本不格式化的同时更改表格中特定字母的颜色。

from docx import Document
from docx.shared import RGBColor

def change_text_color(docx_file, text_to_change, color):
    doc = Document(docx_file)
    color_changed = False
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        if text_to_change in run.text:
                            run.text = run.text[:9]
                            run.font.color.rgb = color
                            color_changed = True
                            break
                    if color_changed:
                        break
                if color_changed:
                    break
            if color_changed:
                    break
        if color_changed:
                    break
    modified_docx_file = "modified.docx"
    doc.save(modified_docx_file)
    print(f"已修改DOCX文件'{docx_file}'中的文本颜色。保存为'{modified_docx_file}'。")

docx_file = "C:\\Users\\RAJAGANESH\\Desktop\\New folder\\897506 1st Sample.docx"
text_to_change = "P.O. No.:" 
color = RGBColor(0, 0, 0)  # 黑色

change_text_color(docx_file, text_to_change, color)
#期望效果是将P.O. No.:的文本颜色更改为黑色,而该单元格中的其余文本保持未格式化。
英文:

If anyone has experience working with the python-docx library or any alternative approaches to accomplish this task, I would greatly appreciate your guidance. Specifically, I'd like to know how to change the color of a specific letter within a table while keeping the rest of the text unformatted.

from docx import Document
from docx.shared import RGBColor

def change_text_color(docx_file, text_to_change, color):
    doc = Document(docx_file)
    color_changed = False
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        if text_to_change in run.text:
                            run.text = run.text[:9]
                            run.font.color.rgb = color
                            color_changed = True
                            break
                    if color_changed:
                        break
                if color_changed:
                    break
            if color_changed:
                    break
        if color_changed:
                    break
    modified_docx_file = "modified.docx"
    doc.save(modified_docx_file)
    print(f"Modified DOCX file '{docx_file}' with the new text color. Saved as '{modified_docx_file}'.")

docx_file = "C:\\Users\\RAJAGANESH\\Desktop\\New folder\7506 1st Sample.docx" 
text_to_change = "P.O. No.:" 
color = RGBColor(0, 0, 0)  # Red color

change_text_color(docx_file, text_to_change, color)
#Expectaion is to keep P.0. No.: to change black in color whereas the remaining text in that cell keeps unformatted. 

答案1

得分: 1

对你的代码进行了许多更改,希望你不会介意。这应该能起作用:

from docx import Document
from docx.shared import RGBColor

def get_runs(doc):
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        yield run

def change_text_color(docx_file, text_to_change, color):
    doc = Document(docx_file)
    color_changed = False

    for run in get_runs(doc):
        if text_to_change in run.text:
            pos = run.text.find(text_to_change)
            text_before = run.text[:pos]
            text_after = run.text[pos + len(text_to_change):]

            run.text = text_before
            new_run = run._parent.add_run(text_to_change)

            # 复制原始运行的字体属性到新运行
            new_run.font.name = run.font.name
            new_run.font.size = run.font.size
            new_run.font.bold = run.font.bold
            new_run.font.italic = run.font.italic
            new_run.font.underline = run.font.underline

            # 设置新颜色
            new_run.font.color.rgb = color

            run._parent.add_run(text_after)

            color_changed = True
            break

    if color_changed:
        modified_docx_file = "modified.docx"
        doc.save(modified_docx_file)
        print(f"修改了DOCX文件'{docx_file}'的文本颜色。保存为'{modified_docx_file}'。")

docx_file = "C:\\Users\\RAJAGANESH\\Desktop\\New folder\\897506 1st Sample.docx"
text_to_change = "P.O. No.:"
color = RGBColor(0, 0, 0)  # 黑色

change_text_color(docx_file, text_to_change, color)

(我在手机上编写这个,还没有测试,因为我不在家,所以如果不起作用,请告诉我)

编辑:
我回到家了。我测试了代码并修复了所有问题。如果有问题,请让我知道。

英文:

Made a lot of changes to your code, hopefully you don't mind that. This should do the trick:

from docx import Document
from docx.shared import RGBColor

def get_runs(doc):
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        yield run

def change_text_color(docx_file, text_to_change, color):
    doc = Document(docx_file)
    color_changed = False

    for run in get_runs(doc):
        if text_to_change in run.text:
            pos = run.text.find(text_to_change)
            text_before = run.text[:pos]
            text_after = run.text[pos + len(text_to_change):]

            run.text = text_before
            new_run = run._parent.add_run(text_to_change)

            # Copy the font properties of the original run to the new run
            new_run.font.name = run.font.name
            new_run.font.size = run.font.size
            new_run.font.bold = run.font.bold
            new_run.font.italic = run.font.italic
            new_run.font.underline = run.font.underline

            # Set the new color
            new_run.font.color.rgb = color

            run._parent.add_run(text_after)

            color_changed = True
            break

    if color_changed:
        modified_docx_file = "modified.docx"
        doc.save(modified_docx_file)
        print(f"Modified DOCX file '{docx_file}' with the new text color. Saved as '{modified_docx_file}'.")

docx_file = "C:\\Users\\RAJAGANESH\\Desktop\\New folder\\897506 1st Sample.docx"
text_to_change = "P.O. No.:"
color = RGBColor(0, 0, 0)  # Black colour

change_text_color(docx_file, text_to_change, color)

(I wrote this on my phone and didn't test it yet because I am not home, so let me know if it doesn't work)

Edit:
I am back home. I tested the code and fixed all the issues with it. Still let me know how it goes.

huangapple
  • 本文由 发表于 2023年6月19日 01:07:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定