1

I’m trying to export a datagridview to an excel. I've found a really good solution ,copy-paste solution , but this exception appears.

This is my code, the same code that the solution I've found.

void botonCP_Click(object sender, EventArgs e)
{
    Microsoft.Office.Interop.Excel.Application xlexcel;
    Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
    Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
    object misValue = System.Reflection.Missing.Value;
    xlexcel = new Microsoft.Office.Interop.Excel.Application();
    xlexcel.Visible = true;
    xlWorkBook = xlexcel.Workbooks.Add(misValue);
    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
    CR.Select();
    xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
halfpastfour.am
  • 5,764
  • 3
  • 44
  • 61
  • 1
    Possible duplicate of [Exception from HRESULT: 0x800A03EC Error triying to PasteSpecial a datagridview-excel](http://stackoverflow.com/questions/7099770/hresult-0x800a03ec-on-worksheet-range) – Mehrzad Chehraz Apr 28 '15 at 08:57
  • I've less than 4K rows. I suppose that is a different error. – Adrián Zúñiga Antón Apr 28 '15 at 09:34
  • That's error 1004, it can mean many things. Works just fine when I try it. Which is odd, passing a Range as the first argument is certainly very unusual. Make sure the clipboard actually contains something pastable and be specific about the format you want to paste, like "Text" instead of CR – Hans Passant Apr 28 '15 at 21:04

1 Answers1

0

In my opinion, interop is infuriatingly irksome to use if you don't need to. Freeing up resources is a PIA and one often seems to encounter these little issues (admittedly, this could be my lack of knowledge on the subject!).

For me, I'd just use a library such as EPPlus to acheive this.

Something like this ought to serve well and would (IMO) be easier to write, manage and debug:

//Get DataGridView into a DataTable:
var bindingSource = (BindingSource)dataGridView.DataSource;
var dataView = (DataView)bindingSource.List;
var dataTable = dataView.Table;

//Create a Spreadsheet
using (ExcelPackage excelPackage = new ExcelPackage())
{
    ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add("DataExport");
    ws.Cells[1,1].LoadFromDataTable(dataTable, PrintHeaders:true);


    //Write to an outputstream:
    excelPackage.SaveAs(outputStream);
    //or filesystem:
    excelPackage.SaveAs(new FileInfo(@"C:\Temp\Export.xlsx"));
}

Much easier!

Stewart_R
  • 13,764
  • 11
  • 60
  • 106