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
Here I used DataTable to write data to excel file. I think data Grid View also same to the DataTable.
First get data from Database:
db.GetData(sqlgetprint);
It's call for method that method is:
class DataBaseConnection
{
private OdbcConnection conn1 = new OdbcConnection(@"FILEDSN=C:/OTPub/Ot.dsn;" + "Uid=sa;" + "Pwd=otdata@123;"); //"DSN=Ot_DataODBC;" + "Uid=sa;" + "Pwd=otdata@123;"
//select
public System.Data.DataTable GetData(string sql)
{
try
{
conn1.Open();
OdbcDataAdapter adpt = new OdbcDataAdapter(sql, conn1);
DataTable dt = new DataTable();
adpt.Fill(dt);
conn1.Close();
return dt;
}
catch (Exception ex)
{
conn1.Close();
throw ex;
}
}
}
After that create Object for DataBaseConncetion Class in your working form
DataBaseConnection db = new DataBaseConnection();
In your Button Click Event you can Write this Code to Write to the Excel file
string sqlgetprint = "SELECT Service_No,Full_name, Acc_No, OP_date, On_time, Off_time, OP_hours, Payment FROM Print_Op ORDER BY Service_No , OP_date";
DataTable dtall = db.GetData(sqlgetprint);
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel Documents (*.xls)|*.xls";
saveFileDialog1.FileName = "Employee Details.xls";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string fname = saveFileDialog1.FileName;
StreamWriter wr = new StreamWriter(fname);
for (int i = 0; i < dtall.Columns.Count; i++)
{
wr.Write(dtall.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dtall.Rows.Count); i++)
{
for (int j = 0; j < dtall.Columns.Count; j++)
{
if (dtall.Rows[i][j] != null)
{
wr.Write(Convert.ToString(dtall.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
//go to next line
wr.WriteLine();
}
//close file
wr.Close();
if (File.Exists(fname))
{
System.Diagnostics.Process.Start(fname);
}
}
}
catch (Exception)
{
MessageBox.Show("Error Create Excel Sheet!");
}