由于客户需求,做了一个导出EXECL,导出的效果为
一级 | 二级 | 三级 |
一类 | ||
食品 | ||
面包 | ||
糖 | ||
又一类 | ||
电子产品 | ||
手机 |
protected void Button1_Click(object sender, EventArgs e)
{
string sql1 = "";
string sql2 = "select *,hzflchina from hzfamx where hzcode='sp_init' and LEN(hzflbh)=1 and hzflbh <>5";//二级栏目的sql语句
/////
//创建一个Table 和 DataSet
DataTable table = new DataTable();
DataSet ds = new DataSet();
//创建列
DataColumn column1 = new DataColumn();
column1.DataType = System.Type.GetType("System.String");
column1.ColumnName = "一级分类";
table.Columns.Add(column1);
DataColumn column2 = new DataColumn();
column2.DataType = System.Type.GetType("System.String");
column2.ColumnName = "二级分类";
table.Columns.Add(column2);
DataColumn column3 = new DataColumn();
column3.DataType = System.Type.GetType("System.String");
column3.ColumnName = "三级分类";
table.Columns.Add(column3);
string two = "";
DataRow row1 = null;
DataRow row2 = null;
DataRow row3 = null;
foreach (DataRow dr in dal.GetDataSet(sql2).Tables[0].Rows)
{
row1 = table.NewRow();
row1["一级分类"] = dr["hzflchina"].ToString().Trim();
table.Rows.Add(row1);
sql1 = "select * from hzfamx where hzcode='sp_init' and LEN(hzflbh)=3 and hzflbh like'" + dr["hzflbh"].ToString().Trim() + "%'";
foreach (DataRow dr1 in dal.GetDataSet(sql1).Tables[0].Rows)
{
row2 = table.NewRow();
row2["二级分类"] = dr1["hzflchina"].ToString().Trim();
table.Rows.Add(row2);
sql1 = "select * from hzfamx where hzcode='sp_init' and LEN(hzflbh)=5 and hzflbh like'" + dr1["hzflbh"].ToString().Trim() + "%'";
foreach (DataRow dr2 in dal.GetDataSet(sql1).Tables[0].Rows)
{
row3 = table.NewRow();
row3["三级分类"] = dr2["hzflchina"].ToString().Trim();
table.Rows.Add(row3);
}
}
}
//把 Table添加到 DataSet 里面去
ds.Tables.Add(table);
ExportResult(ds, "商品分类");
}
public void ExportResult(DataSet ds, string excelName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/ms-excel";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
DataGrid dg = new DataGrid();
dg.DataSource = ds;
dg.DataBind();
dg.RenderControl(htmlWrite);
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(excelName, System.Text.Encoding.UTF8) + ".xls");
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.End();
}