如何在 OPENXML 电子表格单元格中插入换行符?

问题描述 投票:0回答:3

我目前正在使用类似的方法在单元格中插入内联字符串:

new Cell() 
{ 
    CellReference = "E2", 
    StyleIndex = (UInt32Value)4U, 
    DataType = CellValues.InlineString, 
    InlineString = new InlineString(new Text( "some text")) 
}

但是

\n
无法插入换行符,我该怎么做?


回应

new Cell(
         new CellValue("string \n string")
        ) 
    { 
        CellReference = "E2", 
        StyleIndex = (UInt32Value)4U, 
        DataType = CellValues.String         
    }
c# cell openxml spreadsheet line-breaks
3个回答
13
投票

你需要做两件事:

1.) 将单元格标记为“换行文本”。如果您使用现有电子表格作为模板,则可以在电子表格中手动执行此操作。只需右键单击单元格并选择“设置单元格格式..”,单击“对齐”选项卡并选中“自动换行文本”复选框。
或...您可以以编程方式设置 CellFormat。如果您有一个名为“cf”的 CellFormat 对象,您将执行以下操作:

cf.ApplyAlignment = true;//Set this so that Excel knows to use it.
if (cf.Alignment == null)//If no pre-existing Alignment, then add it.
  cf.Alignment = new Alignment() { WrapText = true };
Alignment a = cf.Alignment;
if (a.WrapText == null || a.WrapText.Value == false)
  a.WrapText = new BooleanValue(true);//Update pre-existing Alignment.

2.) 你不应该使用“ ",相反,您应该使用标准的回车+换行组合:" ”
如果您将两者混合(即“ “没有前面的” “ 和 ” "),这应该在填充单元格值之前修复它:

sHeaderText = sHeaderText.Replace("\r\n", "\n").Replace("\n", "\r\n");

我自己不使用 CellValues.String 甚至 CellValues.InlineString
相反,我使用 CellValues.SharedString 构建文本单元格(就像 Excel 一样)。
对于 Bool,我使用“CellValues.Boolean”,对于所有其他(数字和日期),我不设置单元格的 DataType任何东西 - 因为这就是 Excel 在我查看它创建的标记时所做的事情。


6
投票

尝试使用 CellValues.String 而不是 CellValues.InlineString。


0
投票

我的解决方案是:创建

CellFormat
时设置
WrapText = true

new Alignment
{
    Horizontal = HorizontalAlignmentValues.Left,
    Vertical = VerticalAlignmentValues.Center,
    WrapText = true, //This setting
};
© www.soinside.com 2019 - 2024. All rights reserved.