[英]Inserting A Line Break (Not A Paragraph Break) Programatically To A Word Document
[英]Insert paragraph / line break in field - Microsoft Word
我正在嘗試將換行符插入到表格單元格(字段)中,請參見“ w:br /”。 我實際上該怎么做?
我在包含表的文檔中有一個標簽,其中包含一個表格單元格。 我不想復制單元格,而是想在單元格內插入帶換行符的文本。
var row = new XElement("Row");
string annetBeskrivelse = string.Empty;
foreach (var field in table.Elements("Field"))
{
foreach (SPListItem item in listItemCollection)
{
try
{
var listColumnName = field.Attribute("Name").Value;
SPField listField = list.Fields[listColumnName];
annetBeskrivelse += listField.GetFieldValueAsText(item[listColumnName]);
annetBeskrivelse += "<w:br />";
}
catch (ArgumentException)
{
LblErroMessage.Text =
string.Format(
"Invalid template document - refers to list column ({0}) that doesn't exist",
field.Attribute("Name").Value);
}
}
row.Add(new XElement("Field", field.Attribute("Name"),
new XAttribute("Value", annetBeskrivelse)));
table.Add(row);
}
我試過了:
"<w:br />"
"\n"
new Paragraph();
我必須自己用文字處理表格,因此為了使自己更輕松,我為表格編寫了一個包裝器,稱為CustomTable
。 在我的CustomTableCell
我做了以下屬性來獲取/設置內容(包括多行單元格):
public class CustomTableCell
{
public TableCell Cell {get; private set;} //The open xml sdk TableCell class
public string InnerText
{
get { return Cell.InnerText; }
set
{
if (String.IsNullOrEmpty(value))
return;
Paragraph p = Cell.GetFirstChild<Paragraph>();
if (p.ChildElements.Count > 1)
{
Run run = (Run)p.GetFirstChild<Run>().CloneNode(true);
p.RemoveAllChildren<Run>();
run.RemoveAllChildren<Text>();
run.GetMultiLineRun(value);
p.AppendChild(run);
}
else
{
Run run = p.GetFirstChild<Run>();
if (run != null)
run.GetMultiLineRun(value);
else
{
run = new Run();
p.Append(run.GetMultiLineRun(value));
}
}
}
}
}
和GetMultiLineRun
方法:
public static class Extensions
{
public static Run GetMultiLineRun(this Run run, string s)
{
string[] lines =
s.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length > 0)
{
//Don't add break after last line!
foreach (string line in lines.Reverse().Skip(1).Reverse())
{
run.AppendChild(new Text(line));
run.AppendChild(new Break());
}
run.AppendChild(new Text(lines.Last()));
}
return run;
}
}
基本上,如果一個段落中只有一個運行,則更改其內容;如果一個段落中有多個運行,則復制第一個,編輯內容,然后刪除其他內容。 不過,我只需要完全替換單元格中的內容,因此,如果您只想編輯現有內容,則需要對其進行一些調整。
為這樣的東西編寫包裝器確實很方便,因為直接用文字操作表是一場噩夢,而且無法維護。
Paragraph paragraph = new Paragraph();
string[] lines = Value.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
Run run = new Run(new Text(lines[0]));
if (lines.Length > 1)
{
run.AppendChild(new Break());
run.AppendChild(new Text(lines[1]));
}
paragraph.Append(run);
我有一個類似的問題。 我最終將字符串(示例中的變量Value)放入以“ \\ n”作為換行符的單元格中。 我在換行符上將字符串拆分為一個數組。 我的代碼中只有一個中斷的可能性,但是如果您有多個換行符,則可以使用foreach進行遍歷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.