How to properly set Column Width upon creating Excel file? (Column properties)

Rocketq picture Rocketq · Dec 15, 2013 · Viewed 99.6k times · Source

I am using standard library

using Excel = Microsoft.Office.Interop.Excel;

And this is how I create Excel, just small part of code:

//Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Excel._Application xlApp = new Excel.Application();

xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

//add data 
xlWorkSheet.Cells[1, 1] = "";
xlWorkSheet.Cells[1, 2] = "Student1";
xlWorkSheet.Cells[1, 3] = "Student2";
xlWorkSheet.Cells[1, 4] = "Student3";

The problem is that sometimes size of cell can be smaller that text`s size. I tried this one:

Excel.Range chartRange;
chartRange.EntireColumn.ColumnWidth = 31.43;

It works fine, but I need to set this property for each column separately. How I can I do that?

Answer

bto.rdz picture bto.rdz · Dec 15, 2013

I normally do this in VB and its easier because Excel records macros in VB. So I normally go to Excel and save the macro I want to do.

So that's what I did now and I got this code:

Columns("E:E").ColumnWidth = 17.29;

Range("E3").Interior.Pattern = xlSolid;
Range("E3").Interior.PatternColorIndex = xlAutomatic;
Range("E3").Interior.Color = 65535;
Range("E3").Interior.TintAndShade = 0;
Range("E3").Interior.PatternTintAndShade = 0;

I think you can do something like this:

xlWorkSheet.Columns[5].ColumnWidth = 18;

For your last question what you need to do is loop trough the columns you want to set their width:

for (int i = 1; i <= 10; i++) // this will apply it from col 1 to 10
{
    xlWorkSheet.Columns[i].ColumnWidth = 18;
}