How to insert programmatically a new line in an Excel cell in C#?

后端 未结 13 1063
情话喂你
情话喂你 2020-12-30 00:32

I\'m using the Aspose library to create an Excel document. Somewhere in some cell I need to insert a new line between two parts of the text.

I tried \"\\r\\n\" but i

相关标签:
13条回答
  • 2020-12-30 01:10

    Have you tried "\n" I guess, it should work.

    0 讨论(0)
  • 2020-12-30 01:12
    cell.Text = "your firstline<br style=\"mso-data-placement:same-cell;\">your secondline";
    

    If you are getting the text from DB then:

    cell.Text = textfromDB.Replace("\n", "<br style=\"mso-data-placement:same-cell;\">");
    
    0 讨论(0)
  • 2020-12-30 01:13

    What worked for me:

    worksheet.Cells[0, 0].Style.WrapText = true;
    worksheet.Cells[0, 0].Value = yourStringValue.Replace("\\r\\n", "\r\n");
    

    My issue was that the \r\n came escaped.

    0 讨论(0)
  • 2020-12-30 01:14

    You need to insert the character code that Excel uses, which IIRC is 10 (ten).


    EDIT: OK, here's some code. Note that I was able to confirm that the character-code used is indeed 10, by creating a cell containing:

    A

    B

    ...and then selecting it and executing this in the VBA immediate window:

    ?Asc(Mid(Activecell.Value,2,1))
    

    So, the code you need to insert that value into another cell in VBA would be:

    ActiveCell.Value = "A" & vbLf & "B"
    

    (since vbLf is character code 10).

    I know you're using C# but I find it's much easier to figure out what to do if you first do it in VBA, since you can try it out "interactively" without having to compile anything. Whatever you do in C# is just replicating what you do in VBA so there's rarely any difference. (Remember that the C# interop stuff is just using the same underlying COM libraries as VBA).

    Anyway, the C# for this would be:

    oCell.Value = "A\nB";
    

    Spot the difference :-)


    EDIT 2: Aaaargh! I just re-read the post and saw that you're using the Aspose library. Sorry, in that case I've no idea.

    0 讨论(0)
  • 2020-12-30 01:17

    If anyone is interested in the Infragistics solution, here it is.

    1. Use

      Environment.NewLine

    2. Make sure your cell is wrapped

      dataSheet.Rows[i].Cells[j].CellFormat.WrapText = ExcelDefaultableBoolean.True;

    0 讨论(0)
  • 2020-12-30 01:21

    From the Aspose Cells forums: How to use new line char with in a cell?

    After you supply text you should set the cell's IsTextWrapped style to true

    worksheet.Cells[0, 0].Style.WrapText = true;
    
    0 讨论(0)
提交回复
热议问题