-1

I am using this code to write data to excel file.

Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();
excelapp.Visible = true;
I am using this code to write to excel.

_Workbook workbook  = (_Workbook)(excelapp.Workbooks.Open(@"C:\Path\To\Your\WorkBook\ExcelWorkBook.Xls"));
_Worksheet worksheet = (_Worksheet)workbook.ActiveSheet;

worksheet.Cells[1, 1] = "Name";
worksheet.Cells[1, 2] = "Bid";

worksheet.Cells[2, 1] = txbName.Text;
worksheet.Cells[2, 2] = txbResult.Text;

excelapp.Visible = false;

This code works fine except that it works very slowly. I want a fastest way to write tot excel. If I run a loop to write to excel to write thousands of rows, then it works to slowly. Is there any faster way to write the data to excel file like write a whole datatable to excel file of write datatable rows simultaneously rather than cell by cell ?

Harshit
  • 5,147
  • 9
  • 46
  • 93
  • You need to turn calculations off whilst you are updating data. You should stop screen updating. Also, you can paste multi-dimensional arrays directly in. But, perhaps more importantly, you need to release all of the marshalled objects and quit excel when you are done. – Enigmativity Dec 14 '15 at 03:09
  • Use EPPlus, it's the best library to create Excel files in C#. See: http://stackoverflow.com/a/2537778/408710 – lukebuehler Dec 14 '15 at 03:10

1 Answers1

1

Try inserting an array to the excel instead:

    object[,] arr = new object[rowCount, columnCount];
    //Assign your values here

    Excel.Range c1 = (Excel.Range)worksheet.Cells[0, 1];
    Excel.Range c2 = (Excel.Range)worksheet.Cells[rowCount - 1, columnCount];
    Excel.Range range = wsh.get_Range(c1, c2);

    range.Value = arr;

Writing / Reading values to / from each cell is far too slow and will consume a lot of time, try doing it in memory.

User2012384
  • 4,769
  • 16
  • 70
  • 106