Home » excel » c# – Can't use columnwidth excel property

c# – Can't use columnwidth excel property

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to set the width of one or a few cells in Excel.

This is my code

Microsoft.Office.Interop.Excel.Application xla = new    
      Microsoft.Office.Interop.Excel.Application();
Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)xla.ActiveSheet;

i know if i going to change entire columns width

ws.Columns.ColumnWidth = 30;
ws.Cells.ColumnWidth = 30;

but when i try to change spesific columns with this following code

ws.Columns[5].ColumnWidth = 30; 
*//or* 
ws.Cells [5, 5].ColumnWidth = 30;
**//or* 
ws.Columns["E:E"].ColumnWidth = 30;

property ColumnWidth can’t be used
in list after i type colums[5] then dot just appear ‘Equals, GetHahCode, Gettype, ToString’
when i try to manually type it
it’s give error ‘No Overload for method ‘this’ takes ‘1’ argument’

i used visual studio 2010 and framework 4.0
I wonder what I’m missing …

How to&Answers:

You are probably using target framework to be .Net framework 3.5 or lower. Change it to .Net Framework 4.0 and it will work fine. This dynamic property exists only in Framework 4.0. To change framework right click on the project on the solution explorer. Click on properties and set the value for target framework to .NET framework 4.0 using the drop down. This should definitely work. Try and let me know if it doesn’t work for you.

Answer:

You can use MS-Office Macros to get the desired code snippets.

For example i run a simple Macro, then changed the width of the favorite column and at last stopped the macro to view the VB code of this operation.

This is very useful when you are going to do a very complicated task in Ms-Office products.

Sub Macro1()
'
' Macro1 Macro
'

'
    Columns("J:J").ColumnWidth = 22.5
End Sub

The above macro is used to set the width of the column J

Answer:

@Katik: i am able to change the column width using just this

ws.Columns[5].ColumnWidth = 17.57;

May be we will be able to help if you let us know what kind of error or what kind of behavioral change do you see when you use the above statement.