Changing font size of one cell in excel using C#

前端 未结 4 597
孤街浪徒
孤街浪徒 2020-12-19 11:34

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). <

相关标签:
4条回答
  • 2020-12-19 11:52

    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);
       ...
    }
    
    0 讨论(0)
  • 2020-12-19 11:58

    I would just use:

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

    edit: sorry, wrong brackets

    0 讨论(0)
  • 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; 
    
    0 讨论(0)
  • 2020-12-19 12:15

    I had to use:

    worksheet.get_Range("A7", "A7").Cells.Font.Size = 20;
    
    0 讨论(0)
提交回复
热议问题