![](/img/trans.png)
[英]OutOfMemoryException when reading Excel .xlsx file in C# using ExcelLibrary
[英]Excel cell text is trimmed when writen in xlsx file when using C# & OpenXML
在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:c r="A1" t="str">
<x:v xml:space="preserve">
This text starts with a new line</x:v>
</x:c>
xml:space="preserve"
将防止从值的开头或结尾删除空格。 这将产生一个如下所示的文件,您可以看到其中保留了换行符。
而不是同时添加\\r
和\\n
,请尝试仅添加\\r
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.