/// <summary>
/// 导出Excel 李成虎
/// </summary>
/// <param name="dt">DataTable数据集</param>
/// <param name="filePath">模板路径</param>
/// <param name="fileName">文件名</param>
public void DGToExcel(DataTable dt, string filePath, string fileName)
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataGrid excel = new DataGrid();
System.Web.UI.WebControls.TableItemStyle AlternatingStyle = new TableItemStyle();
System.Web.UI.WebControls.TableItemStyle headerStyle = new TableItemStyle();
System.Web.UI.WebControls.TableItemStyle itemStyle = new TableItemStyle();
AlternatingStyle.BackColor = System.Drawing.Color.LightGray;
headerStyle.BackColor = System.Drawing.Color.LightGray;//背景色
headerStyle.Font.Bold = true; //字体
headerStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
itemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center; ;
excel.AlternatingItemStyle.MergeWith(AlternatingStyle);
excel.HeaderStyle.MergeWith(headerStyle);
excel.ItemStyle.MergeWith(itemStyle);
excel.GridLines = GridLines.Both;
excel.HeaderStyle.Font.Bold = true;
excel.DataSource = dt.DefaultView;
excel.DataBind();
excel.RenderControl(htmlWriter);
string filestr = Server.MapPath(filePath);
int pos = filestr.LastIndexOf("\\");
string file = filestr.Substring(0, pos);
if (!Directory.Exists(file))
{
Directory.CreateDirectory(file);
}
System.IO.StreamWriter sw = new StreamWriter(filestr);
sw.Write(stringWriter.ToString());
sw.Close();
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(fileName));
Response.ContentType = "application/ms-excel";
Response.WriteFile(filestr);
Response.End();
}
/// <summary>
/// 导出到Excel lichenghu
/// </summary>
/// <param name="dt"></param>
public static void ToExcel(DataTable dt)
{
string sb = "";
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sb = sb + dr[i].ToString() + "\t";
}
sb = sb + "\n";
}
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=MyExcel.xls");
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
hw.WriteLine(sb.ToString());
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
hw.Flush();
hw.Close();
tw.Flush();
tw.Close();
}