完整程序:
一:调用方法: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 + " "; Response.Output.Write(ls_item); ls_item = string.Empty; ls_item += txtStart.Text + " "; ls_item += DropEnterprise.SelectedItem + " "; 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() + " "; } else { ls_item += dt.Columns[i].ColumnName.ToString() + " "; } } 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() + " "; } else { ls_item += row[i].ToString() + " "; } } //一行一行的写入 Response.Output.Write(ls_item); ls_item = string.Empty; } Response.Output.Flush(); Response.End(); }