Click here to Skip to main content
11,495,724 members (56,073 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0
Hello

I need an opinion again, I have paged datagridview and I need to export data from either desired page or filtered data, that means more pages to excel or csv or whatever, but fast, cause I have many records. I have done with excel in previous of my posts here and it works but it is very slow, how to speed things up

this code works but very very very slow, i fa I need to export say 1000 rows ahhhhh man I can go to dinner , come back and it still isn't finished


Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
 
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
 
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
 
 
app.Visible = true;
 
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
 
for (int i = 1; i < dg1.Columns.Count + 1; i++)
{
   worksheet.Cells[1, i] = dg1.Columns[i - 1].HeaderText;
}
 
for (int i = 0; i < dg1.Rows.Count - 1; i++)
{
   for (int j = 0; j < dg1.Columns.Count; j++)
   {
      worksheet.Cells[i + 2, j + 1] = dg1.Rows[i].Cells[j].Value.ToString();
   }
}

[edit]code block added[/edit]
Posted 17-Nov-12 9:58am
Edited 17-Nov-12 10:05am
Nelek70.7K
v2
Comments
Lacy00 at 19-Nov-12 0:06am
   
If you use Microsoft library, you will get fast reply in msdn forum.
jk0391 at 2 days ago
   
But he's asking here...
F-ES Sitecore at 20 hrs ago
   
Look into the Excel ODBC driver.

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Hi,

you need to set all values at once by using Excel.Range, like this:

// Assuming using Excel = Microsoft.Office.Interop.Excel;

String[,] table = ... // 2D String array of datagrid cells

Excel.Range cell1 = null;
Excel.Range cell2 = null;
Excel.Range range = null;
 
try
{
	// Get range
	cell1 = (Excel.Range)worksheet.Cells[1, 1];
	cell2 = (Excel.Range)worksheet.Cells[numRows, numCols];
	range = worksheet.Range[cell1, cell2];
 
	// Set range value
	range.Value2 = table;
}
finally
{
	// Don't forget to destroy Excel COM objects.
}
  Permalink  
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Dnyaneshwar@Pune 692
1 CHill60 318
2 Sascha Lefèvre 275
3 Nakul Chaudhari 236
4 RyanDev 220
0 Sergey Alexandrovich Kryukov 10,362
1 OriginalGriff 8,821
2 Sascha Lefèvre 3,899
3 Maciej Los 3,422
4 Richard Deeming 2,600


Advertise | Privacy | Mobile
Web03 | 2.8.150520.1 | Last Updated 29 May 2015
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100