Saturday, May 05, 2012

Automatically Sizing Excel Columns

Today while trying to do some formatting on Excel using .Net I came up with an error.

One of the things I tried is to make Excel columns automatically size according to the content having on them. As all of you might know we can get this done in Excel by simply double clicking on the column’s right margin. While doing this in code I got the following exception.

ExcelSheet.get_Range("A1", "E10")' threw an exception of type 'System.Runtime.InteropServices.COMException'
base {System.Runtime.InteropServices.ExternalException}: {"Exception from HRESULT: 0x800401A8"}

The code involved in generating this error is as below.

  1. (ExcelSheet.get_Range("A1", "E10")).EntireColumn.AutoFit();

 

Later I found the reason for this error. Error will occur when we use AutoFit () on empty cells. Because initially I did not have anything in my excel sheet I kept on getting this. So to overcome this error use the same code to auto fit the cell contents simply after the cells are populated with values.

If you cannot get AutoFit () to work the reason might be the same thing. make sure the cells you apply auto fit have some values on them.

The best thing is to use AutoFit () after all data are entered into Excel sheet.

2 comments:

Anonymous said...

I do not even know how I ended up here, but
I thought this post was good. I do not know who you are but certainly you're going to a famous blogger if you are not already ;) Cheers!
Also visit my webpage ... St Paul SEO

Anonymous said...

Hello Dear, are you in fact visiting this web page daily, if
so then you will definitely obtain good know-how.
Here is my blog post cheap seo services