我也来发asp.net 导出Excel

来源:互联网 发布:怎么做好社团知乎 编辑:程序博客网 时间:2024/06/16 07:13

    public void CreateExcel(DataTable table, string FileName)
    {       

        HttpResponse resp;
        resp = Page.Response;
        string filename = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
        resp.Clear();
        resp.Buffer = true;
        resp.Charset = "GB2312";
        resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);
        resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        resp.HeaderEncoding = System.Text.Encoding.UTF8;
        resp.ContentType = "application/ms-excel";

        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlControls.HtmlTable htmltable = new HtmlTable();
        System.Web.UI.HtmlControls.HtmlTableRow tableheadRow = new HtmlTableRow();

        ////表头

        for (int i = 0; i < table.Columns.Count; i++)
        {
            System.Web.UI.HtmlControls.HtmlTableCell tableCell = new HtmlTableCell();
            tableCell.Controls.Add(new LiteralControl(table.Columns[i].Caption.ToString()));
            tableheadRow.Cells.Add(tableCell);
        }

        htmltable.Rows.Add(tableheadRow);

        ////逐行处理数据
        foreach (DataRow row in table.Rows)
        {
            System.Web.UI.HtmlControls.HtmlTableRow tablebodyRow = new HtmlTableRow();
            for (int j = 0; j < table.Columns.Count; j++)
            {
                System.Web.UI.HtmlControls.HtmlTableCell tableCell = new HtmlTableCell();
                tableCell.Controls.Add(new LiteralControl(row[table.Columns[j].ColumnName].ToString()));
                string typestr = SQLUtility.GetDbType(table.Columns[j].DataType).ToString();
                if (typestr.ToUpper() == "INT32" || typestr.ToUpper() == "INT")
                {
                    tableCell.Attributes.Add("style", "vnd.ms-excel.numberformat:#,##0");
                }
                else if (typestr.ToUpper() == "DECIMAL")
                {
                    tableCell.Attributes.Add("style", "vnd.ms-excel.numberformat:#,##0.00");
                }
                else if (typestr.ToUpper() == "DATETIME")
                {
                    tableCell.Attributes.Add("style", "vnd.ms-excel.numberformat:yyyy年MM月dd日");
                }
                else
                {
                    tableCell.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                }
               

                tablebodyRow.Cells.Add(tableCell);
            }

            htmltable.Rows.Add(tablebodyRow);
        }

        htmltable.Border = 1;
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        htmltable.RenderControl(oHtmlTextWriter);
        resp.Output.Write(oStringWriter.ToString());
        resp.Flush();
        resp.End();

}

原创粉丝点击