从gridView导出到C#的最快方法 [英] Fastest way to export from gridView to c#
问题描述
大家好
我正在寻找一种将数据从datagridview导出到Excel工作表的有效方法.这是我正在使用的当前算法:
Hello everyone
I''m searching for an efficient way to export data from a datagridview to an excel sheet. This is the current algorithm i''m working with:
for (int i = 0; i < dgvResult.RowCount; i++)
{
for (int j = 0; j < dgvResult.ColumnCount; j++)
{
DataGridViewCell cell = dgvResult[j, i];
sheet.Cells[i + 2, j + 1] = cell.Value;
}
}
这种方法(嵌套循环)非常慢,因为我的程序将要处理一个巨大的数据库.我需要一种替代方法,该方法在保存Excel工作表时不会让我等待太多.
有任何建议吗?
This method(nested loops) is very slow as my program will be dealing with a huge database. I need an alternative method that won''t keep me waiting too much while the excel sheet is saving.
Any suggestions?
推荐答案
您可以在数组中收集值并将该数组立即推送到 Excel .请参阅此 [ ^ ]线程以获取详细信息.第二个答案(来自Lesmo)包含此想法的C#实现. :)
You can collect your values in array and push this array to Excel at once. See this[^] thread for details. The second answer (from Lesmo) contains a C# implementation of this idea. :)
for (int i = 0; i < table.Rows.Count; i++) {
for (int j = 0; j < table.Columns.Count; j++) {
arr[i, j] = table.Rows[j].ToString();
MessageBox.Show(arr[i, j].ToString());
}
}
该框将打印"System.Data.DataRow"而不是预期值.
The box is printing "System.Data.DataRow" instead of the expected value.
您必须像这样更改代码:
You have to change your code like this:
for (int i = 0; i < table.Rows.Count; i++) {
for (int j = 0; j < table.Columns.Count; j++) {
arr[i, j] = table.Rows[i][j].ToString(); // Change here!!!
MessageBox.Show(arr[i, j].ToString());
}
}
试一试.同样,这不是最快的方法.如果性能仍然不能令人满意,则可以通过缓存使用的数据列来提高性能:请参见此 [ ^ ]发表想法. :)
Give it a try. Also this is not the fastest way. If the performance is still not satisfactory you can improve performance by caching the used data columns: see this[^] post for an idea. :)
这篇关于从gridView导出到C#的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!