How to insert programmatically a new line in an Ex

2019-02-04 06:10发布

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 it doesn't work, just displays two square symbols in cell. I can however press Alt+Enter to create a new line in that same cell.

How do I insert a new line programmatically?

12条回答
冷血范
2楼-- · 2019-02-04 06:26

Using PEAR 'Spreadsheet_Excel_Writer' and 'OLE':

Only way I could get "\n" to work was making the cell $format->setTextWrap(); and then using "\n" would work.

查看更多
贪生不怕死
3楼-- · 2019-02-04 06:28
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;\">");
查看更多
唯我独甜
4楼-- · 2019-02-04 06:28

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.

查看更多
Juvenile、少年°
5楼-- · 2019-02-04 06:28

"\n" works fine. If the input is coming from a multi-line textbox, the new line characters will be "\r\n", if this is replaced with "\n", it will work.

查看更多
贪生不怕死
6楼-- · 2019-02-04 06:33

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;
查看更多
疯言疯语
7楼-- · 2019-02-04 06:36

You can use Chr(13). Then just wrap the whole thing in Chr(34). Chr(34) is double quotes.

  • VB.Net Example:
  • TheContactInfo = ""
  • TheContactInfo = Trim(TheEmail) & chr(13)
  • TheContactInfo = TheContactInfo & Trim(ThePhone) & chr(13)
  • TheContactInfo = Chr(34) & TheContactInfo & Chr(34)
查看更多
登录 后发表回答