Search code examples
c#excelopenxmlopenxml-sdkoffice-automation

OpenXML C# Excel SharedStringItem Inserting new line


I'm using OpenXML to create a formatted block of text with Excel. The requirement is to use predefined styles (set by an admin) to format a block of text. I've managed to accomplish everything by using the SharedStringItem and the Run class. However I'm having trouble figuring out how to preserving the carriage returns "\r\n".

The following code is not producing the run on a new line

private static void NewRun(SharedStringItem sharedString, bool isBullet = false)
{
      var newRun = new Run();

      newRun.Text = new Text { Text = Environment.NewLine };
      sharedString.Append(newRun);
}

private static void NewRun(SharedStringItem sharedString, bool isBullet = false)
{
      var newRun = new Run();

      newRun.Text = new Text { Text = "\r\n" };
      sharedString.Append(newRun);
}

When the above methods are used I can see the SharedStringItem.InnerText is using the new lines however appear to be lost in the markup.

<x:t>Our corporate and commercial litigation

enter image description here

Have I just stumbled upon a limitation of the SharedStringItem or am I missing something?


Solution

  • In order to preserve the new line in the mark up you need to set the following property in the Text class.

    Text { Space = SpaceProcessingModeValues.Preserve }
    

    I used the Open XML SDK Productivity Tool (definitely recommended and can be found here https://github.com/OfficeDev/Open-XML-SDK/releases/tag/v2.5 ) to help me solve this issue.