读书人

将Repeater里面的数据导出到EXCEL中

发布时间: 2013-03-21 10:08:17 作者: rapoo

将Repeater里面的数据导出到EXCEL中,NPOI组件怎么使用
将Repeater里面的数据导出到EXCEL中,NPOI组件怎么使用,有详细的代码更好 excel
[解决办法]
repeater数据源DataSource是DataTable吧,

 public static void TableToExcel(DataTable dt, string fileName, bool saveFile, Encoding ecoding = null)
{
StringWriter stringWriter = new StringWriter();
#region 设置数字为文本形式,避免长数字转为科学计数法而丢失0
string strStyle = "<style>td{mso-number-format:'\\@';}</style>";

stringWriter.WriteLine(strStyle);
#endregion
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataGrid excel = new DataGrid();

TableItemStyle AlternatingStyle = new TableItemStyle();
TableItemStyle headerStyle = new TableItemStyle();
TableItemStyle itemStyle = new TableItemStyle();
headerStyle.Font.Bold = true;

headerStyle.HorizontalAlign = HorizontalAlign.Center;
itemStyle.HorizontalAlign = HorizontalAlign.Left;


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);

int fileN = fileName.LastIndexOf('\\');
string tmpName = fileName.Substring(fileN + 1);

// 文件的保存路径
string DownloadFilePath = fileName;


// 如果需要保存文件则保存文件在服务器端


if (!Directory.Exists(DownloadFilePath) && saveFile)
{
StreamWriter sw = new StreamWriter(DownloadFilePath, false, Encoding.GetEncoding("utf-7"));
sw.Write(stringWriter.ToString());
sw.Close();
}


// 下载文件到客户端

System.Web.HttpContext curContext = System.Web.HttpContext.Current;
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = ecoding == null ? Encoding.GetEncoding("utf-8") : ecoding;
//curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + tmpName);
curContext.Response.AppendHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(tmpName, System.Text.Encoding.UTF8));
curContext.Response.Charset = "";

curContext.Response.Write(stringWriter.ToString());
curContext.Response.End();




}

读书人网 >C#

热点推荐