nissl-lab / npoi

a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support adding line endings when a string containing \n is added to the document

Zt-freak opened this issue · comments

NPOI Version Used

2.6.2

File Type

  • XLSX
  • XLS
  • DOCX
  • XLSM
  • OTHER

Use Case

I want to be able to add line endings to a document, however every line ending \n in the string I want to add gets converted into a space.

I tested with both XWPFParagraph.ReplaceText() and XWPFRun.SetText(), both of them share this \n to spaces conversion behaviour.

Description

I got an example program which calls both XWPFParagraph.ReplaceText() and XWPFRun.SetText():

using NPOI.XWPF.UserModel;

using FileStream rs = File.OpenRead(@"test.docx");

using var doc = new XWPFDocument(rs);

XWPFParagraph firstPara = doc.Paragraphs.First();

firstPara.ReplaceText("{test}", "A\nB\nC\nD");

XWPFRun run = firstPara.CreateRun();
run.TextPosition = 8;
run.SetText("E\nF\nG\nH");

using var ws = File.Create(@"output.docx");
doc.Write(ws);

The document contains one paragraph containing the text:

{test}

The resulting document will contain the following text:

A B C D E F G H

While the desired result would be:

A
B
C
D
E
F
G
H

Hi, you can use AddCarriageReturn() method this way:

string text = "E\nF\nG\nH";
var lines = text.Split("\n");

run.SetText(lines[0]);

for(int i = 1; i < lines.Length; i++)
{
    run.AddCarriageReturn();
    run.AppendText(lines[i]);
}