[c#] How to properly set Column Width upon creating Excel file? (Column properties)

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?

This question is related to c# excel office-interop

The answer is


I did it this way:

var xlApp = new Excel.Application();
var xlWorkBook = xlApp.Workbooks.Add(System.Reflection.Missing.Value);
var xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.Item[1];
xlWorkSheet.Columns.AutoFit();

With this way, columns always fit to text width inside cells.

Hope it helps to someone!


This link explains how to apply a cell style to a range of cells: http://msdn.microsoft.com/en-us/library/f1hh9fza.aspx

See this snippet:

Microsoft.Office.Tools.Excel.NamedRange rangeStyles =
this.Controls.AddNamedRange(this.Range["A1"], "rangeStyles");

rangeStyles.Value2 = "'Style Test";
rangeStyles.Style = "NewStyle";
rangeStyles.Columns.AutoFit();

Excel ColumnWidth from dataGridView:

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

See this snippet: (C#)

    private Microsoft.Office.Interop.Excel.Application xla;
    Workbook wb;
    Worksheet ws;
    Range rg;
    ..........

        xla = new Microsoft.Office.Interop.Excel.Application();
        wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
        ws = (Worksheet)xla.ActiveSheet;
        rg = (Range)ws.Cells[1, 2];
        rg.ColumnWidth = 10;
        rg.Value2 = "Frequency";
        rg = (Range)ws.Cells[1, 3];
        rg.ColumnWidth = 15;
        rg.Value2 = "Impudence";
        rg = (Range)ws.Cells[1, 4];
        rg.ColumnWidth = 8;
        rg.Value2 = "Phase";

I have change all columns width in my case as

            worksheet.Columns[1].ColumnWidth = 7;
            worksheet.Columns[2].ColumnWidth = 15;
            worksheet.Columns[3].ColumnWidth = 15;
            worksheet.Columns[4].ColumnWidth = 15;
            worksheet.Columns[5].ColumnWidth = 18;
            worksheet.Columns[6].ColumnWidth = 8;
            worksheet.Columns[7].ColumnWidth = 13;
            worksheet.Columns[8].ColumnWidth = 17;
            worksheet.Columns[9].ColumnWidth = 17;

Note: Columns in worksheet start with 1 not from 0 as in Arrary.


Use this One

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to excel

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Converting unix time into date-time via excel How to increment a letter N times per iteration and store in an array? 'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data) How to import an Excel file into SQL Server? Copy filtered data to another sheet using VBA Better way to find last used row Could pandas use column as index? Check if a value is in an array or not with Excel VBA How to sort dates from Oldest to Newest in Excel?

Examples related to office-interop

How to properly set Column Width upon creating Excel file? (Column properties) Importing Excel into a DataTable Quickly How to fix 'Microsoft Excel cannot open or save any more documents' What reference do I need to use Microsoft.Office.Interop.Excel in .NET? How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries Reading Datetime value From Excel sheet How to make correct date format when writing data to Excel Create Excel files from C# without office Exporting the values in List to excel C# - How to add an Excel Worksheet programmatically - Office XP / 2003