problem while exporting to excel

Posted by Akiii under C# on 3/21/2011 | Points: 10 | Views : 1621 | Status : [Member] | Replies : 2
namespace Sqltoexcel
{
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=ARKA-PC;Initial Catalog=rgdb;User Id = sa;;password = 12345");
DataTable dt = new DataTable();

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btn1_Click(object sender, EventArgs e)
{
string str = "select * from reg_table";
SqlDataAdapter sda = new SqlDataAdapter(str, conn);
sda.Fill(dt);
exporttosql(dt);
}

public void exporttosql(DataTable dt)
{
HttpContext context = HttpContext.Current;
string attach = "attachment;filename = example.xls";
context.Response.ClearContent();
context.Response.AddHeader("content-disposition",attach);
context.Response.ContentType = "application/ms-excel";
string sep = "";

if (dt != null)
{
foreach(DataColumn dc in dt.Columns)
{
context.Response.Write(sep + dc.ColumnName);
sep = "\t";
}
context.Response.Write(System.Environment.NewLine);

foreach(DataRow dr in dt.Rows)
{
sep = "";
for (int i = 0; i < dt.Columns.Count;i++)
{
context.Response.Write(sep + "\"" + dr.ToString() + "\"");
sep = "\t";
}
context.Response.Write(System.Environment.NewLine);
}
context.Response.End();
}
//lbl1.Text = "Data Transfered";
//lbl1.Visible = true;
}
}
}


The above code is used to export data from sql to excel. The data is exported but i am not getting the desired value. I am providing a screen shot attached of the excel sheet.
Please help me in this....

Thanks and Regards
Akiii




Responses

Posted by: Akiii on: 3/21/2011 [Member] Bronze | Points: 25

Up
0
Down
please refer to the attached file...

Thanks
Akiii
 Download source file

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Akiii on: 3/21/2011 [Member] Bronze | Points: 25

Up
0
Down
the problem is dr.tostring()...

it should be dr and i in third bracket

Thanks and Regards
Akiii

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response