【问题标题】:How to insert line break within OPENXML spreadsheet cell?如何在 OPENXML 电子表格单元格中插入换行符?
【发布时间】:2010-10-18 10:32:35
【问题描述】:

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

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


    【解决方案1】:

    你需要做两件事:

    1.) 将单元格标记为“环绕文本”。如果您使用现有电子表格作为模板,您可以在电子表格中手动执行此操作。只需右键单击单元格并选择“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.
    

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

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

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

    【讨论】:

    • 如何将CellFormat 对象或Alignment 对象应用于给定单元格?
    • 这对我不起作用。我只是在 \r\n 行出现错误,并且 Excel 不会打开带有说明它已损坏的文本的工作表
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多