Recently I encountered a problem when dealing with export word document that needs to be replaced when export data rows either use "\ r \ n" or "^ p" so a variety of ways online, said no solution, "\ n" in here are just a playing out of space, and later found the solution:
xwpfRun.AddBreak(BreakType.TEXTWRAPPING)
xwpfRun.AddBreak(BreakClear.ALL)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
/// <summary>
/// 创建Word文档中表格段落实例和设置表格段落文本的基本样式(字体大小,字体,字体颜色,字体对齐位置)
/// </summary>
/// <param name="document">document文档对象</param>
/// <param name="table">表格对象</param>
/// <param name="fillContent">要填充的文字</param>
/// <param name="paragraphAlign">段落排列(左对齐,居中,右对齐)</param>
/// <param name="rowsHeight">设置文本位置(设置两行之间的行间),从而实现table的高度设置效果 </param>
/// <param name="isBold">是否加粗(true加粗,false不加粗)</param>
/// <param name="fontSize">字体大小</param>
/// <returns></returns>
private
static
XWPFParagraph SetTableParagraphInstanceSetting(XWPFDocument document, XWPFTable table,
string
fillContent, ParagraphAlignment paragraphAlign,
int
rowsHeight,
bool
isBold,
int
fontSize = 10)
{
var
para =
new
CT_P();
XWPFParagraph paragraph =
new
XWPFParagraph(para, table.Body);
//创建表格中的段落对象
paragraph.Alignment = paragraphAlign;
//文字显示位置,段落排列(左对齐,居中,右对齐)
XWPFRun xwpfRun = paragraph.CreateRun();
//创建段落文本对象
xwpfRun.AddBreak(BreakType.TEXTWRAPPING);
//换行
xwpfRun.SetText(fillContent);
xwpfRun.FontSize = fontSize;
//字体大小
xwpfRun.IsBold = isBold;
//是否加粗
xwpfRun.SetFontFamily(
"宋体"
, FontCharRange.None);
//设置字体(如:微软雅黑,华文楷体,宋体)
xwpfRun.SetTextPosition(rowsHeight);
//设置文本位置(设置两行之间的行间),从而实现table的高度设置效果
return
paragraph;
}
|
Achieve results:
Note: This wrap is to change the position of text. So AddBreak () needs to be placed SetText thereby achieving the above effect before ().
I saw someone say xwpfRun.AddCarriageReturn () This can also wrap, but after trying the effect is only space, but also tried to use (char) 11 content wrap, but guided by the word open, being only two more Effective methods;
If you want to specify a new line of cell contents, here we need to put this method to add a parameter to change it
transfer:
effect:
BreakType
reference:
https://www.iteye.com/blog/elim-2037193
https://blog.csdn.net/alai7150/article/details/103802834
https://blog.csdn.net/s1040342522/article/details/78456042
https://www.cnblogs.com/fger/p/11187954.html
https://www.cnblogs.com/sun-flower1314/p/10128796.html
http://poi.apache.org/apidocs/dev/org/apache/poi/xwpf/usermodel/XWPFRun.html