//导出excel
protected void lbtn1_Click(object sender, EventArgs e)
{
string str = DateTime.Now.ToString("yyyyMMddHHmmss");
ExportGv("application/ms-excel", str + "供应商信息.xls");
}
DataGrid dg = new DataGrid();
private void BindToDg()
{
string cnnstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(cnnstr);
string insertcmd = "select * from 供应商";
SqlCommand sc = new SqlCommand(insertcmd, connection);
DataSet ds = new DataSet();
SqlDataAdapter adpt = new SqlDataAdapter(sc);
adpt.Fill(ds);
dg.DataSource = ds.Tables[0];
dg.DataBind();
}
private void ExportGv(string FileType, string FileName)
{
BindToDg();
Response.Clear();
Response.Buffer = true;
//Response.Charset = "utf-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); // 中文
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
//GridView1.Page.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
dg.RenderControl(oHtmlTextWriter);
//Response.Write(style);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
今天做课程设计的时候准备做一个listview数据导出到excel文件,但是没找到可以隐藏我不需要的行列的方法.后来改成在前台加一个隐藏的gridview=.=但是发现导出的excel文件不能读取.最后老师指导着直接在后台建了一个datagrid绑定数据库,但是有一次导出的文件变成乱码,其他时候的又都可以,不造闹哪样"╮( ̄▽ ̄"")╭"