Ste*_*vie 3 c# excel trim cell 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)
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于底层格式是 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);
Run Code Online (Sandbox Code Playgroud)
这会生成如下所示的 XML:
<x:c r="A1" t="str">
<x:v xml:space="preserve">
This text starts with a new line</x:v>
</x:c>
Run Code Online (Sandbox Code Playgroud)
这xml:space="preserve"将防止从值的开头或结尾删除空格。这会生成一个如下所示的文件,您可以在其中看到保留的换行符。
| 归档时间: |
|
| 查看次数: |
1727 次 |
| 最近记录: |