分享

把数据导出到excel中

 周旋图书馆 2014-07-29
 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);
    }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多