Skip to content

Instantly share code, notes, and snippets.

@KOZ60
Last active October 23, 2023 23:49
Show Gist options
  • Save KOZ60/65a47ddf62793715a011e85bc6fc6e7b to your computer and use it in GitHub Desktop.
Save KOZ60/65a47ddf62793715a011e85bc6fc6e7b to your computer and use it in GitHub Desktop.
NetOfficeFw

Would you like to try using NetOfficeFw.Excel? You can get it from nuget.

https://www.nuget.org/packages/NetOfficeFw.Excel

  1. There is no need to write Marshal.ReleaseComObject at all. All objects implement IDisposable, and when you Dispose them, they are released internally using ReleaseComObject. Also, if you Dispose the top level NetOffice.ExcelApi.Application, all the objects under it will be released.

  2. Since it is late binding, it does not depend on the Office version.

■ new file save as.

using Excel = NetOffice.ExcelApi;

using (var xlApp = new Excel.Application()) {
    using (var xlBook = xlApp.Workbooks.Add()) {
        using (Excel.Worksheet xlSheet
                = (Excel.Worksheet)xlBook.Worksheets.Add()) {
            xlSheet.Cells[1, 1].Value = "1";
        }
        xlApp.DisplayAlerts = false;
        xlBook.SaveAs(@"z:\test.xlsx");
    }
    xlApp.Quit();
}

■ Like GetObject in VB

object book = Marshal.BindToMoniker(@"z:\test.xlsx");
Excel.Workbook xlBook = new Excel.Workbook(null, book);
Excel.Application xlApp = xlBook.Application;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment