这是我通过搜了各个文章做出来的,大多数有相同的不要介意哈,我只是做个记录,感觉有点麻烦,但是能做出来
#region 导出按钮事件
protected void btn_export_Click(object sender, EventArgs e)
{
//dt主表信息
if (dt.Rows.Count == 0){
Response.Write("<script>alert('没有数据,不导出!');</script>");
} else{
List<object> ls = new List<object>(); //存放dt主表中订单编号所有的值
foreach (DataRow dr in dt.Rows)
{
ls.Add(dr["orderNumber"]);
}
DataTable dtdd = new DataTable();
for (int i = 0; i < ls.Count; i++)
{
var order = (from o in db.order
join m in db.orderDetail on
o.orderNumber equals m.orderNumber
where o.orderNumber == ls[i].ToString()
select new
{//要显示的字段 订单编号 = o.orderNumber.ToString() }).ToList();
DataTable ddd = LINQToDataTable(order);//linq转datatable
dtdd.Merge(ddd); //合并多个datatable
}
ExcelExport(dtdd, "订单信息"); //导出
}
}
#region 把linq转换成datatable
public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
if (oProps == null) {
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
#endregion
#region datatable导出
protected void ExcelExport(DataTable dtm, string ExportFileName)
{
DataGrid dgExcel = new DataGrid();
dgExcel.DataSource = dtm;
dgExcel.DataBind();
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
string dateStr = DateTime.Now.ToString("yyyyMMddHHmmss");
string fileName = System.Web.HttpUtility.UrlEncode(ExportFileName + "-" + dateStr, System.Text.Encoding.UTF8);
Response.AppendHeader("content-disposition", "attachment;filename=\"" + fileName + ".xls\"");
this.EnableViewState = false;
StringWriter sw = new StringWriter();
HtmlTextWriter htmTextWriter = new HtmlTextWriter(sw);
dgExcel.RenderControl(htmTextWriter);
Response.Write(sw);
Response.End();
}
#endregion
导出部分效果如下:
总共是3步走,1,linq联表查到数据(我这是根据编号循环查到数据,并将这些数据合并到一个datatable中),2,linq转换成datatable,3,导出