使用C#&OpenXML时,在xlsx文件中写入Excel单元格文本时会被修剪

在写入Excel文件时,单元格中的文本在写入后会被修剪。

例如:
比方说,我试图写: "\r\nThis text starts with a new line "我期望当我打开单元格的xlsx文件开始一个空行,而是我得到这个"This text starts with a new line"

这只发生在开始和结束的空白处,基本上被修剪。

我已经尝试设置像这样的单元格格式,但它似乎不工作:

 new CellFormat() { ApplyAlignment = true, Alignment = new Alignment { WrapText = new BooleanValue(false) } } 

问题是基础格式是XML。 除非将空格标记为已保存,否则值的开始或结尾的任何空格都将被忽略。

为此,您需要将Space属性设置为SpaceProcessingModeValues.Preserve ,例如:

 Cell cell = new Cell() { CellReference = "A1" }; CellValue value = new CellValue("\r\nThis text starts with a new line"); value.Space = SpaceProcessingModeValues.Preserve; cell.CellValue = value; cell.DataType = new EnumValue<CellValues>(CellValues.String); 

这产生如下的XML:

 <x:cr="A1" t="str"> <x:v xml:space="preserve"> This text starts with a new line</x:v> </x:c> 

xml:space="preserve"将防止从值的开头或结尾删除空格。 这会生成一个如下所示的文件,您可以在其中看到新行被保留。

显示换行符的Excel输出被保留。

不要同时添加\r\n ,只能尝试添加\r