private void Button4_Click(object sender, System.EventArgs e)
{
string sql=chksql.Text.Replace("*","ch as 序号,fpmc as 发票名称,fpph as 发票批次,fpme as 发票面额, '['+ fphm+']' as 发票号码,'['+fpmm+']' as 发票密码,dxmz as 奖金大写,sxmz as 奖金小写,ljr as 领奖人,zjmc as 证件名称,'['+zjhm+']' as 证件号码,djr as 兑奖人,dqmc as 地区名称"
;
SqlConnection Sqlcn=new SqlConnection(CN.constr);
Sqlcn.Open();
SqlDataAdapter dt=new SqlDataAdapter(sql,Sqlcn);
DataSet ds=new DataSet();
dt.Fill(ds,"tb"
;
DataTable2Excel(ds.Tables["tb"] );
Sqlcn.Close();
}
public static void DataTable2Excel(System.Data.DataTable dtData)
{
System.Web.UI.WebControls.DataGrid dgExport = null;
// 当前对话
// IO用于导出并返回excel文件
if (dtData != null)
{
// 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
dgExport = new System.Web.UI.WebControls.DataGrid();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls"
;
HttpContext.Current.Response.Charset ="gb2312";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
dgExport.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
dgExport.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
}