What is the fastest way to export DataGridView rows in the range of 460328 - 800328 to Excel or into an SQL Server database table with out using Microsoft office interop as interop is quite slow and heavy on system resources?
What is the fastest way to export DataGridView rows in the range of 460328 - 800328 to Excel or into an SQL Server database table with out using Microsoft office interop as interop is quite slow and heavy on system resources?
This may be faster way,
using Excel = Microsoft.Office.Interop.Excel;
public static void SaveGridToExcel(DataGridView DGV)
{
if (DGV.Rows.Count > 0)
{
string filename = "";
SaveFileDialog SV = new SaveFileDialog();
SV.Filter = "EXCEL FILES|*.xlsx;*.xls";
DialogResult result = SV.ShowDialog();
if (result == DialogResult.OK)
{
filename = SV.FileName;
bool multiselect = DGV.MultiSelect;
DGV.MultiSelect = true;
DGV.SelectAll();
DGV.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
Clipboard.SetDataObject(DGV.GetClipboardContent());
var results = System.Convert.ToString(Clipboard.GetData(DataFormats.Text));
DGV.ClearSelection();
DGV.MultiSelect = multiselect;
Microsoft.Office.Interop.Excel.Application XCELAPP = null;
Microsoft.Office.Interop.Excel.Workbook XWORKBOOK = null;
Microsoft.Office.Interop.Excel.Worksheet XSHEET = null;
object misValue = System.Reflection.Missing.Value;
XCELAPP = new Excel.Application();
XWORKBOOK = XCELAPP.Workbooks.Add(misValue);
XCELAPP.DisplayAlerts = false;
XCELAPP.Visible = false;
XSHEET = XWORKBOOK.ActiveSheet;
XSHEET.Paste();
XWORKBOOK.SaveAs(filename, Excel.XlFileFormat.xlOpenXMLWorkbook);
XWORKBOOK.Close(false);
XCELAPP.Quit();
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(XSHEET);
System.Runtime.InteropServices.Marshal.ReleaseComObject(XWORKBOOK);
System.Runtime.InteropServices.Marshal.ReleaseComObject(XCELAPP);
}
catch { }
}
}
}
For me, the best improvement to increase the speed was using this way.
private const string connectionString = "OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=MYDBSERVER;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=SERVERID;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DBName";
object misValue = System.Reflection.Missing.Value;
Excel.Application xlsApp = new Excel.Application();
Excel.Workbook xlsWorkbook = xlsApp.Workbooks.Add(misValue);
Excel.Worksheet myWS = xlsWorkbook.Sheets[1];
Excel.ListObject lo = myWS.ListObjects.AddEx(Excel.XlListObjectSourceType.xlSrcQuery, connectionString, true,
Excel.XlYesNoGuess.xlGuess, myWS.Range["A5"]);
//A5 is the starting cell
lo.QueryTable.CommandText = "SELECT * FROM TABLE";
lo.Refresh();
I tried DataReader/Datatable with "for" loop (writting each cell) and both were too much slow recovering a query with 5800 rows (and 40 columns). In numbers:
DataReader - 5:16 minutes
This way - 13 seconds