Skip to content

Excel Interop Code Examples

Asbjørn Skødt edited this page Aug 8, 2022 · 20 revisions

Writing code in C# with Excel Interop.

All code examples begin and end with

using Excel = Microsoft.Office.Interop.Excel;

Excel.Application app = new Excel.Application(); // Create Excel object instance
app.DisplayAlerts = false; // Don't display any Excel prompts
Excel.Workbook wb = app.Workbooks.Open(input_filepath); // Create workbook instance

[ANY CODE EXAMPLE]

wb.Save(); // Save workbook
wb.Close(); // Close workbook
app.Quit(); // Quit Excel application

Find if spreadsheet has sheets

int count = wb.Worksheets.Count;
if (count = 0)
{
    Console.WriteLine("Spreadsheet has no sheets");
}

Find and remove data connections

int count_conn = wb.Connections.Count;
if (count_conn > 0)
{
    for (int i = 1; i <= wb.Connections.Count; i++)
    {
        wb.Connections[i].Delete();
        i = i - 1;
    }
    count_conn = wb.Connections.Count;
    Console.WriteLine("--> Data connections detected and removed");
}

Remove author, subject and comments from file property details

if (wb.Author != "" || wb.Title != "" || wb.Subject != "" || wb.Keywords != "" || wb.Comments != "")
{
    Console.WriteLine("--> Removed file property details");
}

wb.Author = ""; // Remove author information
wb.Title = ""; // Remove title information
wb.Subject = ""; // Remove subject information
wb.Keywords = ""; // Remove keywords information
wb.Comments = ""; // Remove comments information

Convert to .xlsx Strict

wb.SaveAs(filepath, 61); // Save workbook as .xlsx Strict
wb.Save(); // You can delete this line, you do not need to save again