Two quick points:
First: Make sure you're cleaning up your Interop objects properly. It's not easy. See here for more. The first answer has good advice: never use two dots with COM objects. Many of your lines violate this, for example excelWorksheet.UsedRange.Columns[1]
. Keep everything in a variable that you can later release.
var usedRange = excelWorksheet.UsedRange;var columns = usedRange.Columns;var column1 = columns[1];//Do workMarshal.ReleaseComObject(column1);Marshal.ReleaseComObject(columns);Marshal.ReleaseComObject(usedRange);
Release your objects this way Marshal.ReleaseComObject(object);
Second: I find it best to keep all of my Excel library code hidden in a Facade. In this way your isolating the complicated code that accesses the Excel library from the code that's generating the spreadsheet. This makes it easy to switch libraries in the future. You never know when your situation will change and you'll want to use EPPlus instead of Excel.Interop for Excel work. Or Aspose. Or NPOI. The Excel Interop library requires the computer to have Excel running on it. If you deploy your code to a server that doesn't have Excel, you'll have to dig through your code to replace your Interop calls with 3rd party calls. Don't forget that while Interop references are 1-based, many popular Excel libraries used 0-based references. It's much easier to abstract this away in a Facade.