[英]Excel cell text is trimmed when writen in xlsx file when using C# & OpenXML
When writing inside an excel file the text in the cell gets trimmed after writing. 在excel文件中写入时,写入后会修剪单元格中的文本。
For example: 例如:
Let's say I am trying to write : "\\r\\nThis text starts with a new line "
I would expect when I open the xlsx file for the cell to start with an empty line, but instead I get this "This text starts with a new line"
假设我要写:
"\\r\\nThis text starts with a new line "
我期望在打开单元格的xlsx文件时以空行开头,但我却得到了这样的信息"This text starts with a new line"
This happens only to the whitespace at the beginning and the end, which essentially gets trimmed. 这仅在开始和结尾的空白处发生,而空白基本上已被修剪。
I have tried setting the cell format like this but it doesn't seem to work: 我尝试过像这样设置单元格格式,但似乎不起作用:
new CellFormat()
{
ApplyAlignment = true,
Alignment = new Alignment
{
WrapText = new BooleanValue(false)
}
}
The problem is that the underlying format is XML. 问题在于基础格式是XML。 Any whitespace at the start or end of a value is ignored unless you mark the space as preserved.
除非将空格标记为保留,否则将忽略值开头或结尾的所有空格。
To do this you need to set the Space
property to SpaceProcessingModeValues.Preserve
, for example: 为此,您需要将
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);
This produces XML that looks like: 这样生成的XML看起来像:
<x:c r="A1" t="str">
<x:v xml:space="preserve">
This text starts with a new line</x:v>
</x:c>
The xml:space="preserve"
will prevent the whitespace from being removed from the beginning or end of the value. xml:space="preserve"
将防止从值的开头或结尾删除空格。 This produces a file that looks like the below where you can see the newline is preserved. 这将产生一个如下所示的文件,您可以看到其中保留了换行符。
而不是同时添加\\r
和\\n
,请尝试仅添加\\r
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.