Use the Excel Export API to Create a Column

  • 2 minutes to read

The example below demonstrates how to create and modify a column in a worksheet. To do this, use the IXlSheet.CreateColumn method. To specify where a created column should be located in a worksheet, pass a zero-based column index to the method as a parameter.

// Create a new worksheet.
using (IXlSheet sheet = document.CreateSheet())
{
    // Create the column "A" and set its width to 100 pixels.
    using (IXlColumn column = sheet.CreateColumn())
    {
        column.WidthInPixels = 100;
    }

    // Create the column D and set its width to 24.5 characters.
    using (IXlColumn column = sheet.CreateColumn(3))
    {
        column.WidthInCharacters = 24.5f;
    }
}

Note

The number of columns in a worksheet is permanently fixed and depends on the output file format (16,384 columns for XLSX and CSV files, and 256 columns for XLS files). Note that you can use the IXlDocumentOptions.MaxColumnCount property to obtain the maximum number of columns supported by the file format to which the document is exported.

Important

Columns in a worksheet should be created prior to rows and cells. If you try to create a column after or during the row generation, an InvalidOperationException exception will be thrown.