How to solve error 0x80029C4A while exporting data from C# to Excel?

166 Views Asked by At

I'm using Visual Studio 2022 Community. On my pc there is Microsoft Office 2013. I installed "Microsoft.Office.Interop.Excel" version 15.0.0.0; Runtime version v2.0.50727.

I'm trying to export data into excel using this code:

using Excel = Microsoft.Office.Interop.Excel;

// [...]

private void exportExcel() {
    Excel.Application excelApp = new Excel.Application();
    
    Excel.Workbook workbook = excelApp.Workbooks.Add();
    Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];

    string[,] data =
    {
        {"Nome", "Cognome", "Età"},
        {"Mario", "Rossi", "30"},
        {"Luigi", "Verdi", "25"},
        {"Paola", "Bianchi", "28"}
    };
    
    for (int i = 0; i < data.GetLength(0); i++)
    {
        for (int j = 0; j < data.GetLength(1); j++)
        {
            worksheet.Cells[i + 1, j + 1] = data[i, j];
        }
    }
    
    string path = System.Reflection.Assembly.GetEntryAssembly().Location;
    path = path.Substring(0, path.LastIndexOf("\\"));
    path += "\\data.xlsx";
    
    workbook.SaveAs(path);
    workbook.Close();
    excelApp.Quit();
}

And I'm getting an error on the line

Excel.Workbook workbook = excelApp.Workbooks.Add();

This is the error System.InvalidCastException: 'Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).'

What can I do?

I searched for a solution but didn't find anything that could help me.

1

There are 1 best solutions below

1
mokhtar sayed On

you can make an Extension Method

   /// <summary>
    /// This is an extension method that can be used with any collection to write it to an excel workbook
    /// </summary>
    /// <param name="items">The collection of items to export</param>
    /// <typeparam name="T">The item entity type</typeparam>
    /// <returns>An excel workbook that can be written to a memory stream and downloaded or sent via email</returns>
    public static XLWorkbook ExportExcelWorkbook<T>(this IEnumerable<T> items)
    {
        var workBook = new XLWorkbook();
        var workSheet = workBook.Worksheets.Add("sheet1");
        workSheet.Cell(1, 1).InsertTable(items);

        return workBook;
    }

And use it like this Blockquote

  var workBook = IEnumerable.ExportExcelWorkbook();

        return File(WriteExcelToMemoryStream(workBook),
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            $"file.xlsx");