I'm trying to generate an excel file from a datagrid, and this is generating the following error:
Anunhandledexceptionoftype'System.InvalidCastException'occurredinEletronicTaxNotes.exeAdditionalinformation:TheCOMobjectoftype'Microsoft.Office.Interop.Excel.ApplicationClass'cannotbeconvertedintheinterfacetype'Microsoft.Office.Interop.Excel._Application'.ThisoperationfailedbecausetheQueryInterfacecallontheCOMcomponentfortheinterfacewithIID'{000208D5-0000-0000-C000-000000000046}'failedduetothefollowingerror:Errorloadingthelibrary/DLLoftype.(ExceptionfromHRESULT:0x80029C4A(TYPE_E_CANTLOADLIBRARY)).
privatevoidExportarExcel2(){//CreatingaExcelobject.Excel._Applicationexcel=newExcel.Application();if(excel==null){MessageBox.Show("Excel is not properly installed!!"); return;
}
Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
try
{
Excel._Worksheet worksheet = workbook.ActiveSheet;
worksheet.Name = "ExportedFromDatGrid";
worksheet.Cells[1, 0] = "Codigo";
worksheet.Cells[1, 1] = "Descrição";
worksheet.Cells[1, 2] = "Fornecedor";
worksheet.Cells[1, 3] = "Quantidade";
worksheet.Cells[1, 4] = "Preço";
worksheet.Cells[1, 5] = "Preço Total";
worksheet.Cells[1, 6] = "Ncm";
worksheet.Cells[1, 7] = "Nota";
worksheet.Cells[1, 8] = "DataDocumento";
worksheet.Cells[1, 9] = "Tipo";
// Passa as celulas do DataGridView para a Pasta do Excel
for (var i = 0; i <= gridItens.RowCount - 1; i++)
{
for (var j = 0; j <= 9; j++)
{
DataGridViewCell cell = j <= 2 ? gridItens[j, i] : gridNotas[j, i];
worksheet.Cells[i + 2, j + 1] = cell.Value;
}
}
//Getting the location and file name of the excel to save from user.
var saveDialog = new SaveFileDialog
{
Filter = @"Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*",
FilterIndex = 2
};
if (saveDialog.ShowDialog() != DialogResult.OK) return;
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show(@"Export Successful");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
}
}
I followed the following suggestions to include the appropriate references:
What reference do I need to use Microsoft.Office.Interop.Excel in .NET?
Can not find Microsoft.Office.Interop Visual Studio
Ialsotriedothersuggestions,whichistodeleteaduplicaterecordthatcouldbecausingtheerror:
Error Printing When Using Microssoft.office.interop
But the record that is giving error does not exist in my records, as shown below:
Likewise,thefollowingsuggestionsdidnothelpeither:
Error accessing COM components
Class not registered error when creating Excel workbook in C #
Unfortunately, none of this has any effect, and the result is always the same:
I'm running out of options to move on. I imagined that such a task would be something simple to do. Does anyone have any other suggested solution that can help me?