Sean Bailey
Sean Bailey

Reputation: 375

Set Column Width in C# (Interop.Excel)

I have a c# script which successfully opens a specified Excel workbook, delete the first row and save it down as a csv format.

I have an issue that the CSV saves down as a standard col width of 8.43 I would like to change the col width of col J as 17.00 before saving down the csv.

Can someone please advise how I set the Col width of col J to 17.

I am unable to use VBA / Macros due to the process.

I am using;

myWorkSheet.Columns["J:J"].ColumnWidth = 17.57;

This however leads to an object does not contain definition for 'ColumnWidth' screenshot attached. enter image description here

Full code below;

        public void DeleteRows(string OriginalFileName,String NewFileName)
    {
        Microsoft.Office.Interop.Excel.Application myApp;
        Microsoft.Office.Interop.Excel.Workbook myWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet myWorkSheet;
        Microsoft.Office.Interop.Excel.Range range;
        myApp = new Microsoft.Office.Interop.Excel.Application();
        myWorkBook = myApp.Workbooks.Open(OriginalFileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        myWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)myWorkBook.Worksheets.get_Item(1);
        range = (Microsoft.Office.Interop.Excel.Range)myWorkSheet.Application.Rows[1, Type.Missing];
        range.Select();
        range.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);
        //Microsoft.Office.Interop.Excel.Range ThisRange1 = myWorkSheet.get_Range("J:J",System.Type.Missing);
        myWorkSheet.Columns["J:J"].ColumnWidth = 17.57; //ERRORLINE
        myApp.DisplayAlerts = false;
        myWorkSheet.SaveAs(NewFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, false, false, false, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
        myWorkBook.Close(false);
        myApp.Quit();
    }

Upvotes: 3

Views: 11632

Answers (1)

Aousaf Rashid
Aousaf Rashid

Reputation: 5758

I don't think you need to set a range for this :

 Using Excel=Microsoft.Office.Interop.Excel;
 Excel.Worksheet myWorkSheet = new Excel.Worksheet;

 myWorkSheet.Columns["J:J"].ColumnWidth = 17.57;

///Or set width to AutoFit

 myWorkSheet.Columns.AutoFit();

Upvotes: 6

Related Questions