i am trying to export the data from the ACCDB file to Excel .
and its working but exported excel file is empty there is no data.
Below is code
What I have tried:
}
private void btnExport_Click(object sender, EventArgs e)
{
ExportToExcel(dataGridView1,"ExportedUserDetail");
}
public void ExportToExcel(DataGridView gridviewID, string excelFilename)
{
DateTime from = dateTimePicker1.Value;
string date1 = from.ToString("MM/dd/yyyy");
string fromdate = date1 + " " + "12:00:00" + " " + "AM";
DateTime to = dateTimePicker2.Value;
string date2 = to.ToString("MM/dd/yyyy");
string todate = date2 + " " + "11:00:00" + " " + "PM";
if (dateTimePicker1.Value != dateTimePicker2.Value)
{
string ConnString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Data\Test.accdb";
DataTable Data = new DataTable();
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("select tb3.SeqNo as 'Session Sequence Number',tb3.SessionDate as 'Session Date',tb3.CustomerName as 'Customer Name',tb3.RepID as 'Rep ID',tb3.RepName as 'Rep Name',CaseRef as 'Ticket No',PracticeName as 'Practice Name',PostCode as 'Post Code',PhoneManner as 'Phone Manner',Satisfaction,iif (Satisfaction='EXCELLENT',5, iif (Satisfaction='VERY GOOD' ,4, iif (Satisfaction='GOOD' ,3, iif (Satisfaction='NEUTRAL' ,2, iif (Satisfaction='POOR' ,1))))) as Ratings,Ratings/5*100 as 'Percentage' , Consultant,CustomerComments as 'Customer Comments',Recommendation from tb1,tb3 where tb3.SeqNo=tb1.SeqNo and tb3.SessionDate between #" + fromdate + "# and #" + todate + "#", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(Data);
conn.Close();
dataGridView1.DataSource = Data;
Microsoft.Office.Interop.Excel.Application objexcelapp = new Microsoft.Office.Interop.Excel.Application();
objexcelapp.Application.Workbooks.Add(Type.Missing);
objexcelapp.Columns.ColumnWidth = 25;
for (int i = 1; i < gridviewID.Columns.Count + 1; i++)
{
objexcelapp.Cells[1, i] = gridviewID.Columns[i - 1].HeaderText;
}
for (int i = 0; i < gridviewID.Rows.Count; i++)
{
for (int j = 0; j < gridviewID.Columns.Count; j++)
{
if (gridviewID.Rows[i].Cells[j].Value != null)
{
objexcelapp.Cells[i + 2, j + 1] = gridviewID.Rows[i].Cells[j].Value.ToString();
}
}
}
MessageBox.Show("Your excel file exported successfully at d:\\" + excelFilename + ".xlsx");
objexcelapp.ActiveWorkbook.SaveCopyAs("d:\\" + excelFilename + ".xlsx");
objexcelapp.ActiveWorkbook.Saved = true;
}
}
else
{
MessageBox.Show("Please select valid date...!!!");
}
}
}
}