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

Viewed 122534

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?

7 Answers

Use this One

 ((Excel.Range)oSheet.Cells[1, 1]).EntireColumn.ColumnWidth = 10;

Excel ColumnWidth from dataGridView:

           foreach (DataGridViewColumn co in dataGridView1.Columns)
           { worksheet.Columns[co.Index + 1].ColumnWidth = co.Width/8; }
Related