简体   繁体   English

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

[英]How to insert line break within OPENXML spreadsheet cell?

I'm currently using something like this to insert inline string in a cell :我目前正在使用这样的东西在单元格中插入内联字符串:

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

But \\n doesn't work to insert line break, how can i do this?但是\\n不能插入换行符,我该怎么做?


The response响应

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

You need to do two things:你需要做两件事:

1.) Mark the cell as "Wrapped Text". 1.)将单元格标记为“Wrapped Text”。 You can do this in the spreadsheet by hand if you are using an existing spreadsheet as your template.如果您使用现有电子表格作为模板,则可以在电子表格中手动执行此操作。 Just right-click on the cell(s) and select " Format Cells.. ", click on the " Alignment " tab and check the " Wrap Text " checkbox.只需右键单击单元格并选择“设置单元格格式.. ”,单击“对齐”选项卡并选中“换行文本”复选框。
OR... You can set the CellFormat programmatically.或...您可以以编程方式设置 CellFormat。 If you have a CellFormat object called " cf ", you would do something like this:如果您有一个名为“ 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.) You shouldn't use "\\n", instead you should be using the standard carriage-return + line-feed combination: "\\r\\n" 2.)你不应该使用“\\n”,而应该使用标准的回车+换行组合:“\\r\\n”
If you are mixing the two (ie "\\n" without the preceeding "\\r" and "\\r\\n"), this should fix it before populating the cell value:如果您将两者混合(即“\\n”没有前面的“\\r”和“\\r\\n”),这应该在填充单元格值之前修复它:

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

I, myself, do not use CellValues.String or even CellValues.InlineString .我自己不使用CellValues.String甚至CellValues.InlineString
Instead I build my text cells using CellValues.SharedString (just like Excel does).相反,我使用CellValues.SharedString构建我的文本单元格(就像 Excel 那样)。
For Bool I use " CellValues.Boolean ", and for all others (numerics and dates) I do not set the cell's DataType to anything - because that is what Excel does when I look at the markup it creates.对于 Bool,我使用“ CellValues.Boolean ”,而对于所有其他(数字和日期),我没有将单元格的DataType设置为任何内容 - 因为当我查看它创建的标记时,Excel 就是这样做的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM