Docx 请问怎么把 多个docx文件合并成一个文件

并且每个文件要单独新建一个写入,每个文件都会有页眉页脚信息

1 Like

@hhh1111

要将多个 DOCX 文件合并为一个文件,并确保每个文件都有独立的页眉和页脚信息,您可以使用 Aspose.Words 的 AppendDocument 方法。以下是一个示例代码,展示了如何实现这一点:

using Aspose.Words;

class Program
{
    static void Main(string[] args)
    {
        // 创建一个新的文档作为目标文档
        Document dstDoc = new Document();

        // 假设您有多个源文档的路径
        string[] sourceFiles = { "Document1.docx", "Document2.docx", "Document3.docx" };

        foreach (string file in sourceFiles)
        {
            // 加载源文档
            Document srcDoc = new Document(file);

            // 将源文档追加到目标文档
            dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
        }

        // 保存合并后的文档
        dstDoc.Save("MergedDocument.docx");
    }
}

在这个示例中,我们首先创建一个新的目标文档,然后循环遍历每个源文档,将其追加到目标文档中。使用 ImportFormatMode.KeepSourceFormatting 可以确保源文档的格式(包括页眉和页脚)被保留。最后,合并后的文档被保存为 “MergedDocument.docx”。

您可以根据需要调整源文档的路径和目标文档的名称。这样,您就可以将多个 DOCX 文件合并为一个文件,并保持每个文件的独立格式信息。

如果您需要更多关于合并文档的详细信息,可以参考 Aspose.Words 的官方文档。

101005-COVID-19肺炎.docx (46.8 KB)

请问我怎么删除这个文件的 **安慰剂给药到受试者101005前面的数据包括分页符 和换行

@hhh1111 您也可以尝试使用Merger要合并文档,请执行以下操作:

Merger.merge("output.docx", ["input_1.docx", "input_2.docx"])

你的意思是从文档中删除除页眉/页脚之外的所有数据吗?您可以使用:

doc = aw.Document("input.docx")

for section in doc.sections:
    section = section.as_section()
    section.body.remove_all_children()
    if section != doc.sections[0]:
        section.remove()

doc.save("output.docx")

不是是删除文件里面的表格

@hhh1111 它应该删除文件中的所有内容。

不是。你看我上传的文件 我要删除 安慰剂给药到最下面的表格数据

@hhh1111 这是一个带有文本的表,看起来您想删除此表。您可以使用以下代码删除文本和表格。如果你想删除其他内容,你可以勾选previous_siblingnext_sibliing并将其删除。

# Define the text to remove
text_to_remove = "安慰剂给药"

# Iterate through all Run nodes in the document
for run in doc.get_child_nodes(aw.NodeType.RUN, True):
    run = run.as_run()
    # Check if the Run's text matches the text to remove
    if run.text == text_to_remove:
        # Remove the Run from its parent
        table = run.get_ancestor(aw.NodeType.TABLE)
        table.as_table().remove()

doc.save("output.docx")

需要删除他下面的所有表格信息

@hhh1111 您可以像这样更新之前的代码以找到下一个表:

doc = aw.Document("input.docx")

table = None
text_to_remove = "安慰剂给药"

# Iterate through all Run nodes in the document
for run in doc.get_child_nodes(aw.NodeType.RUN, True):
    run = run.as_run()
    # Check if the Run's text matches the text to remove
    if run.text == text_to_remove:
        # Remove the Run from its parent
        table = run.get_ancestor(aw.NodeType.TABLE)

if table is not None:
    tables = doc.get_child_nodes(aw.NodeType.TABLE, True)
    target_index = tables.index_of(table)

    # Check if there is a next table
    if target_index + 1 < tables.count:
        next_table = tables[target_index + 1]
        next_table.remove()

doc.save("output.docx")

也不对啊 没删掉

@hhh1111 这是我提供的代码的输出文件此处以及你提供的文件。您描述的表格已被删除。

output.docx (40.9 KB)

没有

我需要删除下面所有内容。

保留这里内容

@hhh1111 作为一种变体,您可以使用书签删除表格后面和段落前面的所有内容:

doc = aw.Document("input.docx")

table = None
text_to_remove = "安慰剂给药"

# Iterate through all Run nodes in the document
for run in doc.get_child_nodes(aw.NodeType.RUN, True):
    run = run.as_run()
    # Check if the Run's text matches the text to remove
    if run.text == text_to_remove:
        # Remove the Run from its parent
        table = run.get_ancestor(aw.NodeType.TABLE)

start = aw.BookmarkStart(doc, "Bookmark")
end = aw.BookmarkEnd(doc, "Bookmark")

if table is not None:
    table.parent_node.insert_after(start, table)
    tables = doc.get_child_nodes(aw.NodeType.TABLE, True)
    last_table = tables[tables.count - 1]
    last_table.parent_node.insert_after(end, last_table)

bookmark = doc.range.bookmarks.get_by_name("Bookmark")
bookmark.text = ""
bookmark.remove()

doc.save("output.docx")

这是一个基于表信息的文件示例。你也可以在没有last_table信息的情况下工作,只需在文本中找到你需要的段落,并在它之前插入书签的末尾。

请问怎么读取文档的超链接。怎么在把超链接写入另一个文档里面

@hhh1111 “Aspose.Words”将超链接显示为字段。您可以使用以下代码阅读它们:

doc = aw.Document("input.docx")

# 遍历文档中的所有字段起始节点。
for field in doc.range.fields:
    # 检查该字段是否为超链接。
    if field.type == aw.fields.FieldType.FIELD_HYPERLINK:
        # 将字段转换为FieldHyperlink。
        hyperlink = field.as_field_hyperlink()

        # 打印超链接目标并显示文本。
        print(f"Hyperlink Target: {hyperlink.address}")
        print(f"Display Text: {hyperlink.result}")

要插入超链接,您可以使用:

doc = aw.Document()
builder = aw.DocumentBuilder(doc)

builder.font.style_identifier = aw.StyleIdentifier.HYPERLINK
builder.insert_hyperlink("Google Example", "https://www.google.com", False)

doc.save("output.docx")
import aspose.words as aw
import re
import aspose.pydrawing as drawing
lic = aw.License()
lic_path = "../Aspose.Total.Product.Family.lic"
lic.set_license(lic_path)
def clean_content(content):
    # 移除特殊的字段代码和控制字符
    content = re.sub(r'[\x13\x14\x15]', '', content)
    content = content.strip()
    return content
def extract_document_content(doc_path):
    doc = aw.Document(doc_path)
    data_list = []
    # 遍历文档中的所有节点
    for node in doc.get_child_nodes(aw.NodeType.ANY, True):
        print(node.node_type)

        if node.node_type == aw.NodeType.FIELD_START:
            field_start = node.as_field_start()
            field = field_start.as_field_start().get_field()
            # 判断字段类型是否为超链接
            if field.type == aw.fields.FieldType.FIELD_HYPERLINK:
                # 将字段转换为超链接字段
                hyperlink = field.as_field_hyperlink()
                # # 获取超链接地址
                url = hyperlink.address
                data_list.append({"type": "hyperlink", "content": url})
                #
                print("找到一个超链接,地址为:", url)
                # 获取超链接的显示文本
                # display_text = ""
                # current_node = field_start.next_sibling
                # while current_node is not None and current_node.node_type != aw.NodeType.FIELD_END:
                #     if current_node.node_type == aw.NodeType.RUN:
                #         display_text += current_node.get_text()
                #     current_node = current_node.next_sibling
                #
        elif node.node_type == aw.NodeType.PARAGRAPH:
            node = node.as_paragraph()
            content = node.get_text().strip()
            if content and not node.get_ancestor(aw.NodeType.FIELD_START) and 'https:' not in content:
                data_list.append({"type": "paragraph", "content": content})
    return data_list
def save_docx(save_path,data):
    doc = aw.Document()
    builder = aw.DocumentBuilder(doc)
    for item in data:
        content = clean_content(item.get('content', ''))

        if item['type'] == 'paragraph':
            # 添加段落
            builder.writeln(content)
        elif item['type'] == 'hyperlink':
            # 插入超链接
            builder.font.color = drawing.Color.blue
            builder.font.underline = aw.Underline.SINGLE
            builder.insert_hyperlink(content, content, False)

            builder.writeln()
            # 清除字体格式
            builder.font.clear_formatting()

    # 保存文档
    doc.save(save_path)


if __name__ == '__main__':
    doc_path = "../narrative/情報源URL.docx"  # 请替换为您的文档路径
    content_list = extract_document_content(doc_path)
    save_docx("output.docx",content_list)
    print(content_list)

为什么我获取段落信息 也有超链接的信息啊

elif node.node_type == aw.NodeType.PARAGRAPH: 这个判断怎么排出超链接的信息

@hhh1111 在您提供的代码中,如果段落有超链接,则将跳过此操作,只添加超链接信息。请详细说明您的需求?