簡體   English   中英

使用C#和OpenXML寫入xlsx文件時,會修剪Excel單元格文本

[英]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"將防止從值的開頭或結尾刪除空格。 這將產生一個如下所示的文件,您可以看到其中保留了換行符。

顯示換行符的Excel輸出將保留。

而不是同時添加\\r\\n ,請嘗試僅添加\\r

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM