为有中文需求的客户提供多渠道中文技术支持.

Fri Mar 01, 2024 6:17 am

你好,
我想在整篇文档的中间位置插入一段文本, 使用下面的代码插入了文本, 但不是在新段中插入的,而是追加的, 如何按段的方式插入?
还有个问题就是, 如果是多个节, 下面的只会插到第1节的中间, 怎样准确的在多节的段落中间位置后插入新段文本?
谢谢

```
using Spire.Doc;

// 加载文档
Document document = new Document();
document.LoadFromFile(file.FullName);

Section section = document.Sections[0];
// 获取段落数量
int paragraphCount = section.Paragraphs.Count;
Console.WriteLine($"段落数量:{paragraphCount}");

// 计算插入位置(在所有段落的中央位置插入)
int insertIndex = (int)Math.Ceiling(paragraphCount / 2.0);
Console.WriteLine($"插入位置:{insertIndex}");

// 插入段落文本
string textToInsert = "我是添加的文本";
Paragraph paragraph = section.Paragraphs[insertIndex];
TextRange textRange = paragraph.AppendText(textToInsert);
textRange.CharacterFormat.FontName = "微软雅黑";
textRange.CharacterFormat.FontSize = 14;


```

LiuMing111
 
Posts: 2
Joined: Sat Jan 13, 2024 3:08 am

Fri Mar 01, 2024 7:02 am

您好,

感谢您的咨询。
我检查了你的代码,发现你新添加的文本只是在章节的中间段落追加,而不是新建段落来添加文本。另外,如果要想Word文档的所有章节中都添加新文本,需要遍历Word文档的所有章节。请参考下面修改后的代码。
Code: Select all
// 加载文档
Document document = new Document();
document.LoadFromFile("输入文档.docx");
//循环遍历Word文档的所有章节
for (int i =0; i < document.Sections.Count; i++)
{
    //获取章节
    Section section = document.Sections[i];
    // 获取段落数量
    int paragraphCount = section.Paragraphs.Count;
    Console.WriteLine($"段落数量:{paragraphCount}");
    // 计算插入位置(在所有段落的中央位置插入)
    int insertIndex = (int)Math.Ceiling(paragraphCount / 2.0);
    Console.WriteLine($"插入位置:{insertIndex}");
    // 实例化一个新段落并设置文本和样式
    string textToInsert = "我是添加的文本";
    Paragraph paragraph = new Paragraph(document);
    TextRange textRange = paragraph.AppendText(textToInsert);
    textRange.CharacterFormat.FontName = "微软雅黑";
    textRange.CharacterFormat.FontSize = 14;
    //在指定位置插入新段落
    section.Paragraphs.Insert(insertIndex-1, paragraph);
}
document.SaveToFile("结果文件.docx", FileFormat.Docx2016);

Sincerely,
Annika
E-iceblue support team
User avatar

Annika.Zhou
 
Posts: 1651
Joined: Wed Apr 07, 2021 2:50 am

Return to 中文技术支持

cron