Excel 当使用 C# 和 OpenXML 写入 xlsx 文件时,单元格文本被剪裁
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)
}
}
不要同时添加 \r
和 \n
,而是尝试仅添加 \r
。
问题在于基础格式是 XML。值开头或结尾处的任何白色 space 都将被忽略,除非您将 space 标记为保留。
为此您需要将 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"
将防止从值的开头或结尾删除白色space。这会生成一个如下所示的文件,您可以在其中看到保留了换行符。
在 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)
}
}
不要同时添加 \r
和 \n
,而是尝试仅添加 \r
。
问题在于基础格式是 XML。值开头或结尾处的任何白色 space 都将被忽略,除非您将 space 标记为保留。
为此您需要将 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"
将防止从值的开头或结尾删除白色space。这会生成一个如下所示的文件,您可以在其中看到保留了换行符。