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

12

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

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         
    }
2个回答

14

你需要做两件事:

1.) 将单元格标记为“自动换行”。如果你使用现有的电子表格作为模板,可以通过手动右键单击单元格并选择“格式化单元格...”,然后点击“对齐”选项卡并勾选“自动换行”复选框来实现。
OR... 如果你想以编程方式设置单元格格式,则可以设置一个名为“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.) 不应使用"\n",而应该使用标准的回车 + 换行组合:"\r\n"
如果你混用这两个符号(即没有前置的"\r"和"\r\n"),在填充单元格值之前应该将其修正:

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

我个人不使用CellValues.String甚至CellValues.InlineString
相反,我使用CellValues.SharedString构建我的文本单元格(就像Excel一样)。
对于布尔值,我使用“CellValues.Boolean”,而对于所有其他类型的值(数字和日期),我不设置单元格的DataType - 因为当我查看它创建的标记时,这就是Excel所做的。


2
如何将CellFormat对象或Alignment对象应用于给定单元格? - Panzercrisis
1
这对我不起作用。我只是在带有\r\n的行上收到一个错误,Excel无法打开带有文本的工作表,显示它已损坏。 - johnstaveley

6

请使用CellValues.String而不是CellValues.InlineString。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接