aspx文件中:
<asp:Button
ID="btndc" runat="server" Text="导出到excel" onclick="btndc_Click" /> aspx.cs文件中
//调用excel操作类
#region 导出到excel public void ExportToExcel(DataTable Table1) { try { StringWriter sw = new StringWriter(); string[] temStr = new string[Table1.Rows.Count + 1]; for (int i = 0; i < Table1.Columns.Count; i++) { if (i > 0)
{ temStr[0] += "\t"; }
temStr[0] += Table1.Columns[i].ColumnName; } string ss = temStr[0].ToString(); sw.WriteLine(temStr[0].ToString()); for (int j = 0; j < Table1.Rows.Count; j++) //写内容 { for (int k = 0; k < Table1.Columns.Count; k++) { if (k > 0) { temStr[j + 1] += "\t"; }
if (k == 18) { temStr[j + 1] += "公司档案略"; } else { temStr[j + 1] += Table1.Rows[j][k]; } } sw.WriteLine(temStr[j + 1].ToString()); } sw.Close(); Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("客户资源.xls", Encoding.UTF8).ToString()); Response.ContentType = "application/excel"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Response.Write(sw); Response.Flush(); Response.End(); }
catch (Exception ex) { ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + ex.Message + "');</script>"); } } #endregion protected void btndc_Click(object sender, EventArgs e)
{ DataTable dt = CompanyBll.GetAllCompany(); ExportToExcel(dt); } |
|