Connect to Excel then format within a cell

  • Thread starter Thread starter Brian Parker
  • Start date Start date
B

Brian Parker

I need to format text in cell in an Excel worksheet and I need to do this using C#.

I've seen code that will set the format for the whole cell, but I just need to format one character
in that cell.

Example:
The cell has this text in it: H20

I need to use C# to change the "2" to be a subscript.

A similar question was asked before, but I don't think the reply answered the part about only
formatting part of the text in the cell:

( the link will probably wrap )
http://groups.google.com/group/micr..._frm/thread/feaee4eccb1364e4/d6501f0007c0b0f3

TIA for any help on this.
-BEP
 
Brian Parker said:
I need to format text in cell in an Excel worksheet and I need to do this using C#.

I've seen code that will set the format for the whole cell, but I just need to format one character
in that cell.

Example:
The cell has this text in it: H20

I need to use C# to change the "2" to be a subscript.

A similar question was asked before, but I don't think the reply answered the part about only
formatting part of the text in the cell:

( the link will probably wrap )
http://groups.google.com/group/micr..._frm/thread/feaee4eccb1364e4/d6501f0007c0b0f3

TIA for any help on this.
-BEP

Brian,

You can use the method called get_Charaters(start, numberOfChars) to get a
range of characters in a cell. Then, apply whatever formatting you wish to
just that set of chars via the Font property.

Here is some sample code that subscripts the second char on cell B4.

Hope this helps,
Jason Vermillion

Excel.Application app = new Excel.ApplicationClass();
app.Visible = true;

app.Workbooks.Open(@"c:\temp\Book1.xls", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Excel.Worksheet wks = (Excel.Worksheet) app.Sheets["Sheet1"];
wks.get_Range("B4", Type.Missing).set_Value(Type.Missing, "ZZZZZZZ");
wks.get_Range("B4", Type.Missing).get_Characters(2,1).Font.Subscript = true;
 
You can use the method called get_Charaters(start, numberOfChars) to get a
range of characters in a cell. Then, apply whatever formatting you wish to
just that set of chars via the Font property.

*snip*

Thanks, Jason. Exactly what I needed.

-BEP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top