asp.net后台导出excel的方法:使用response导出excel
完整程序:
一:调用方法:CreateExcel(newDt, "application/ms-excel", "FileName");
/// <summary> /// DataTable中的数据导出到Excel并下载 /// </summary> /// <param name="dt">要导出的DataTable</param> /// <param name="FileType">类型</param> /// <param name="FileName">Excel的文件名</param> public void CreateExcel(DataTable dt, string FileType, string FileName) { Response.Clear(); Response.Charset = "UTF-8"; Response.Buffer = true; Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\""); Response.ContentType = FileType; string colHeaders = string.Empty; string ls_item = string.Empty; DataRow[] myRow = dt.Select(); int i = 0; int cl = dt.Columns.Count; //写入方法一 //写入标题等信息 ls_item += Label2.Text + "\t\t\t\n\n"; Response.Output.Write(ls_item); ls_item = string.Empty; ls_item += txtStart.Text + "\t\t\t"; ls_item += DropEnterprise.SelectedItem + "\n"; Response.Output.Write(ls_item); ls_item = string.Empty; //写入段标题 for (i = 0; i < cl; i++) { if (i == (cl - 1)) { ls_item += dt.Columns[i].ColumnName.ToString() + "\n"; } else { ls_item += dt.Columns[i].ColumnName.ToString() + "\t"; } } Response.Output.Write(ls_item); ls_item = string.Empty; foreach (DataRow row in myRow) { for (i = 0; i < cl; i++) { if (i == (cl - 1)) { ls_item += row[i].ToString() + "\n"; } else { ls_item += row[i].ToString() + "\t"; } } //一行一行的写入 Response.Output.Write(ls_item); ls_item = string.Empty; } Response.Output.Flush(); Response.End(); }