Sudheer Kumar

Sudheer Kumar

  • NA
  • 105
  • 10.5k

exporting gridview data to excel getting columncount as zero

Aug 31 2015 2:29 AM
protected void Button1_Click(object sender, EventArgs e)
{
OracleConnection conn = new OracleConnection(oradb);
OracleCommand cmd = new OracleCommand();
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.BindByName = true;
//cmd.Parameters.Add(new OracleParameter("BranchID",BranchId));
OracleParameter transdate1= new OracleParameter();
transdate1.OracleDbType = OracleDbType.Date;
transdate1.Value = TextBox1.Text;
transdate1.ParameterName = "transdate1";
cmd.Parameters.Add(transdate1);
OracleParameter transdate2 = new OracleParameter();
transdate2.OracleDbType = OracleDbType.Date;
transdate2.Value = TextBox2.Text;
transdate2.ParameterName = "transdate2";
cmd.Parameters.Add(transdate2);
cmd.CommandText = "select * from cust_details where transdate between :transdate1 and :transdate2";
OracleDataAdapter od = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
od.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
//Response.Write("Connected to Oracle" + conn.ServerVersion);
// Close and Dispose OracleConnection object
lblDisplay.Text = "connected";
conn.Close();
//Response.Write("Disconnected");
}
protected void Button2_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "Exported from gridview";
// storing header part in Excel
for (int i = 1; i <GridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = GridView1.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int j = 0; j < GridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] =GridView1.Rows[i].Cells[j];
}
}

Answers (1)