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

bel*_*laz 8 c# spreadsheet line-breaks cell openxml

我目前使用这样的东西在单元格中插入内联字符串:

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

但是\n插入换行符不起作用,我该怎么做呢?

谢谢


响应

new Cell(
         new CellValue("string \n string")
        ) 
    { 
        CellReference = "E2", 
        StyleIndex = (UInt32Value)4U, 
        DataType = CellValues.String         
    }
Run Code Online (Sandbox Code Playgroud)

Mik*_*Vee 10

你需要做两件事:

1.)将单元格标记为"Wrapped Text".如果您使用现有电子表格作为模板,则可以手动在电子表格中执行此操作.只需右键单击单元格并选择" Format Cells .. ",单击" Alignment "选项卡,然后选中" Wrap Text "复选框.
或者......您可以通过编程方式设置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.
Run Code Online (Sandbox Code Playgroud)

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

sHeaderText = sHeaderText.Replace("\r\n", "\n").Replace("\n", "\r\n");
Run Code Online (Sandbox Code Playgroud)

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

  • 如何将“CellFormat”对象或“Alignment”对象应用于给定单元格? (2认同)

cdo*_*ner 6

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