使用C#& amp;时在xlsx文件中写入时修剪Excel单元格文本OpenXML的

时间:2016-01-27 15:45:34

标签: c# excel cell openxml trim

在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)
    }
}

2 个答案:

答案 0 :(得分:1)

问题是底层格式是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"将阻止从值的开头或结尾删除空格。这将生成一个类似于下面的文件,您可以在其中看到保留换行符。

Excel output showing the newline is retained.

答案 1 :(得分:0)

请尝试仅添加\r,而不是同时添加\n\r