获取包含特定文本字符串的表的格式,并创建具有相同格式的新表
本文关键字:格式 创建 新表 字符串 文本 包含特 获取 | 更新日期: 2023-09-27 18:15:28
使用c#中的OpenXML,我们需要:
- 查找Word文档中的特定文本字符串(此文本将始终存在于表格单元格)
- 获取文本格式和文本所在的表。
- 创建一个具有相同文本和表格格式的新表,同时从嵌套的List中为单元格拉入文本值
这是我目前拥有的代码和我不确定如何做的地方:
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileWordFile, true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
Body body = mainPart.Document.Body;
IEnumerable paragraphs = body.Elements<Paragraph>();
Paragraph targetParagraph = null;
//Comment 1: Loop through paragraphs and search for a specific string of text in word document
foreach (Paragraph paragraph in paragraphs) {
if(paragraph.Elements<Run>().Any()) {
Run run = paragraph.Elements<Run>().First();
if(run.Elements<Text>().Any()) {
Text text = run.Elements<Text>().First();
if (text.Text.Equals("MY SEARCH STRING")) {
targetParagraph = paragraph;
// Comment 2: How can I get the formatting of the table that contains this text??
}
}
}
}
//Comment 3: Create table with same formatting as where the text was found
Table table1 = new Table();
TableProperties tableProperties1 = new TableProperties();
//Comment 4: How can I set these properties to be the same as the one found at "Comment 2"??
wordDoc.Close();
wordDoc.Dispose();
}
如果您正在寻找表格单元格内的文本元素,您可以使用LINQ查询快速到达那里,而无需使用一堆嵌套循环。
// Find the first text element matching the search string
// where the text is inside a table cell.
var textElement = body.Descendants<Text>()
.FirstOrDefault(t => t.Text == searchString &&
t.Ancestors<TableCell>().Any());
一旦有了匹配项,复制包含所有格式和内容的表最简单的方法就是简单地克隆它。
if (textElement != null)
{
// get the table containing the matched text element and clone it
Table table = textElement.Ancestors<Table>().First();
Table tableCopy = (Table)table.CloneNode(deep: true);
// do stuff with copied table (see below)
}
之后,您可以向复制表的相应单元格添加内容。您所说的"从嵌套列表中为单元格拉入文本值"(什么列表?),所以我只展示一个人为的例子。(这段代码将取代上面代码中的"do stuff"注释。)
// find the table cell containing the search string in the copied table
var targetCell = tableCopy.Descendants<Text>()
.First(t => t.InnerText == searchString)
.Ancestors<TableCell>()
.First();
// get the properties from the first paragraph in the target cell (so we can copy them)
var paraProps = targetCell.Descendants<ParagraphProperties>().First();
// now add new stuff to the target cell
List<string> stuffToAdd = new List<string> { "foo", "bar", "baz", "quux" };
foreach (string item in stuffToAdd)
{
// for each item, clone the paragraph properties, then add a new paragraph
var propsCopy = (ParagraphProperties)paraProps.CloneNode(deep: true);
targetCell.AppendChild(new Paragraph(propsCopy, new Run(new Text(item))));
}
最后,您需要将复制的表添加到文档的某个地方,否则您将看不到它。你没有在你的问题中说你希望它出现在哪里,所以我就把它放在文档的末尾。您可以使用InsertAfter
, InsertAt
, InsertBefore
等方法来插入相对于其他元素的表。
body.AppendChild(tableCopy);