Changing font size of one cell in excel using C#

2020-02-12 08:57发布

I am working on a project that writes data to an Excel file.

Everything is finished now, however I need a few cells with a bigger size than the rest (title, etc).

I have read about this about the internet, but I keep having the same problem: when I execute my code (see below for what I have tried), everything in the worksheet becomes larger.

What I already have tried:

worksheet.Rows[1].Cells[7].Style.Font.Size = 20; 

worksheet.get_Range("A7", "A7").Style.Font.Size = 20;

None of this seems to work; what is the correct way to increase a cell's font size?

标签: c# excel
4条回答
看我几分像从前
2楼-- · 2020-02-12 09:39

I had to use:

worksheet.get_Range("A7", "A7").Cells.Font.Size = 20;
查看更多
该账号已被封号
3楼-- · 2020-02-12 09:42

I would just use:

worksheet.Range["A7"].Style.Font.Size = 20;

edit: sorry, wrong brackets

查看更多
太酷不给撩
4楼-- · 2020-02-12 09:46

If the data is consistent and will always be written to the same cells then this is the simplest solution - works well for product details / contact info type exporting

// set cell A7
worksheet.get_Range("A7", "A7").Font.Size = 20;

// set cells A7, A8
worksheet.get_Range("A7", "A8").Font.Size = 20;

// set cells A7, B7
worksheet.get_Range("A7", "B7").Font.Size = 20;

// set cells A7, A8, B7, B8
worksheet.get_Range("A7", "B8").Font.Size = 20;

If the data varies and will sometimes be written to multiple rows/columns then something like this is more simple - works well for dataset / shopping list type exporting

int RowNum;
int ColNum;

// some code to set variables

worksheet.Cells[RowNum, ColNum].Font.Size = 20; 
查看更多
Root(大扎)
5楼-- · 2020-02-12 09:55

When working with interop excel, try not to write your code with "two dots" in order to clean interop excel objects. This also helps having your code more readable. Anyway, to answer your question, and using what I have pointed out... all you have to do is:

//Declare your variables
Application excel = null;
Workbook excelworkBook = null;
Range excelCellrange = null;
Worksheet worksheet = null;
Font excelFont =null;

//start your application
excel = new Application();
try
{
   ...
   //your code goes here...
   excelCellrange = worksheet.Range[worksheet.Cells[1,7],worksheet.Cells[1,7]];
   excelFont = excelCellrange.Font;
   excelfont.Size = 20;
   ...
   ...
}
catch(Exception ex){
}
finally{
   //here put something to clean the interop objects as the link above.
   ...
   Marshal.ReleaseComObject(excelfont);
   ...
}
查看更多
登录 后发表回答