使用c#将纯文本(标题)导出为ex​​cel

时间:2012-09-13 18:39:14

标签: c# sql-server-2008 export-to-excel

使用C#,Visual Studio 2008& .NET Framework 3.5。我可以直接从DataGridView导出记录到excel,问题是我需要导出其他数据(纯文本)。

这是我的擅长:

Excel table without header

这就是我需要显示标题(表格顶部的行)的方法:

excel with more info

这就是我现在正在做的事情:

protected void btnExcel_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition","attachment;filename=InformeEstudios.xls");
    Response.ContentType = "application/vnd.xls";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    myGridView1.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.End();
}
public override void  VerifyRenderingInServerForm(Control control)
{
     //base.VerifyRenderingInServerForm(control);
}

//MY METHOD
private void BinData()
{
    SqlConnection conex = new SqlConnection("Data Source=xx.xxx.x.xx;Initial   
    Catalog=MYDATABASE;User ID=MYUSER;Password=MYPASS");
    SqlDataAdapter ad = new SqlDataAdapter("select ROW1, ROW2 from MYTABLE", conex);
    DataSet ds = new DataSet();
    ad.Fill(ds);
    myGridView1.DataSource = ds;
    myGridView1.DataBind();
}

如何实现这一点,如何手动编写这两个标题行。提前谢谢!

1 个答案:

答案 0 :(得分:0)

control.RenderControl(...)只是输出html。所以首先输出你自己的html然后调用rendercontrol。