Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


The response

new Cell(
         new CellValue("string \n string")
        ) 
    { 
        CellReference = "E2", 
        StyleIndex = (UInt32Value)4U, 
        DataType = CellValues.String         
    }
like image 993
belaz Avatar asked Apr 08 '09 22:04

belaz


People also ask

Can you do a line break within a cell in Excel?

To start a new line of text or add spacing between lines or paragraphs of text in a worksheet cell, press Alt+Enter to insert a line break. Double-click the cell in which you want to insert a line break (or select the cell and then press F2). Click the location inside the selected cell where you want to break the line.


2 Answers

You need to do two things:

1.) Mark the cell as "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. If you have a CellFormat object called "cf ", you would do something like this:

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"
If you are mixing the two (i.e. "\n" without the preceeding "\r" and "\r\n"), this should fix it before populating the cell value:

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

I, myself, do not use CellValues.String or even CellValues.InlineString.
Instead I build my text cells using CellValues.SharedString (just like Excel does).
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.

like image 120
MikeTeeVee Avatar answered Sep 21 '22 04:09

MikeTeeVee


Try CellValues.String instead of CellValues.InlineString.

like image 32
cdonner Avatar answered Sep 23 '22 04:09

cdonner