private void ToExcel(System.Data.DataTable dt_Data, string fileName) { fileName = fileName + ".xls"; try { HttpResponse resp; resp = Page.Response; resp.Buffer = true; resp.ClearContent(); resp.ClearHeaders(); resp.Charset = "utf-8"; resp.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); resp.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));//否则在IE8下乱码 resp.ContentEncoding = System.Text.Encoding.Default;//设置输出流为简体中文 resp.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 string colHeaders = "", ls_item = ""; for (int i = 0; i < dt_Data.Columns.Count; i++) { if (i == (dt_Data.Columns.Count - 1))//最后一列,加n { colHeaders += dt_Data.Columns[i].Caption.ToString() + "\n"; } else { colHeaders += dt_Data.Columns[i].Caption.ToString() + "\t"; } } resp.Write(colHeaders); //向HTTP输出流中写入取得的数据信息 //逐行处理数据 for (int i = 0; i < dt_Data.Rows.Count; i++) { for (int j = 0; j < dt_Data.Columns.Count; j++) { // ls_item += dt_Data.Rows[i][dt_Data.Columns[i].Caption].ToString().Trim() + "\n"; // ls_item += dt_Data.Rows[i][dt_Data.Columns[i].Caption].ToString().Trim() + "\t"; if (j == dt_Data.Columns.Count - 1)//最后一列,加n { ls_item += dt_Data.Rows[i][dt_Data.Columns[j].Caption].ToString().Trim() + "\n"; } else { ls_item += dt_Data.Rows[i][dt_Data.Columns[j].Caption].ToString().Trim() + "\t"; } } resp.Write(ls_item); ls_item = ""; } resp.End(); } catch (Exception ex) { } finally { #region 强行杀死最近打开的Excel进程 System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL"); System.DateTime startTime = new DateTime(); int m, killId = 0; for (m = 0; m < excelProc.Length; m++) { if (startTime < excelProc[m].StartTime) { startTime = excelProc[m].StartTime; killId = m; } } if (excelProc.Length > 0) { if (excelProc[killId].HasExited == false) { excelProc[killId].Kill(); } } #endregion } }