C#實現GridView導出Excel

来源:http://www.cnblogs.com/rushme/archive/2017/03/24/6613987.html
-Advertisement-
Play Games

using System.Data;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;using System.Text; namespace DotNet.Utilities{ ...


using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

namespace DotNet.Utilities
{
    /// <summary>
    /// Summary description for GridViewExport
    /// </summary>
    public class GridViewExport
    {
        public GridViewExport()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static void Export(string fileName, GridView gv)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", fileName));
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            //HttpContext.Current.Response.Charset = "utf-8";


            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a form to contain the grid
                    Table table = new Table();
                    table.GridLines = GridLines.Both;  //單元格之間添加實線

                    //  add the header row to the table
                    if (gv.HeaderRow != null)
                    {
                        PrepareControlForExport(gv.HeaderRow);
                        table.Rows.Add(gv.HeaderRow);
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in gv.Rows)
                    {
                        PrepareControlForExport(row);
                        table.Rows.Add(row);
                    }

                    //  add the footer row to the table
                    if (gv.FooterRow != null)
                    {
                        PrepareControlForExport(gv.FooterRow);
                        table.Rows.Add(gv.FooterRow);
                    }

                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }
        }

        /// <summary>
        /// Replace any of the contained controls with literals
        /// </summary>
        /// <param name="control"></param>
        private static void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    PrepareControlForExport(current);
                }
            }
        }


        /// <summary>
        /// 導出Grid的數據(全部)到Excel
        /// 欄位全部為BoundField類型時可用
        /// 要是欄位為TemplateField模板型時就取不到數據
        /// </summary>
        /// <param name="grid">grid的ID</param>
        /// <param name="dt">數據源</param>
        /// <param name="excelFileName">要導出Excel的文件名</param>
        public static void OutputExcel(GridView grid, DataTable dt, string excelFileName)
        {
            Page page = (Page)HttpContext.Current.Handler;
            page.Response.Clear();
            string fileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(excelFileName));
            page.Response.AddHeader("Content-Disposition", "attachment:filename=" + fileName + ".xls");
            page.Response.ContentType = "application/vnd.ms-excel";
            page.Response.Charset = "utf-8";

            StringBuilder s = new StringBuilder();
            s.Append("<HTML><HEAD><TITLE>" + fileName + "</TITLE><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>");

            int count = grid.Columns.Count;

            s.Append("<table border=1>");
            s.AppendLine("<tr>");
            for (int i = 0; i < count; i++)
            {

                if (grid.Columns[i].GetType() == typeof(BoundField))
                    s.Append("<td>" + grid.Columns[i].HeaderText + "</td>");

                //s.Append("<td>" + grid.Columns[i].HeaderText + "</td>");

            }
            s.Append("</tr>");

            foreach (DataRow dr in dt.Rows)
            {
                s.AppendLine("<tr>");
                for (int n = 0; n < count; n++)
                {
                    if (grid.Columns[n].Visible && grid.Columns[n].GetType() == typeof(BoundField))
                        s.Append("<td>" + dr[((BoundField)grid.Columns[n]).DataField].ToString() + "</td>");

                }
                s.AppendLine("</tr>");
            }

            s.Append("</table>");
            s.Append("</body></html>");

            page.Response.BinaryWrite(System.Text.Encoding.GetEncoding("utf-8").GetBytes(s.ToString()));
            page.Response.End();
        }

    }
}


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 首先需要明白一個原理: 游戲畫面(動畫)是由一幀幀的圖片載入完成的,並且是連續的。也就是說,在一個時間節點上,一定存在一幀圖片。不同的是每幀的圖片存在的時間不同,如果每幀圖片存在的時間比較短,也即單位時間內幀數比較多的話(幀率大),畫面越流暢。下麵連續的表示圖片的流動,圖片的寬度表示該圖片存在的時間 ...
  • using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Runtim ...
  • 測試環境 操作系統:Windows8.1 開發工具:Unity5.5.2 1、新建一個測試項目,觀測引用System.Xml與Mono.Xml解析文件正確性,與打包後APK體積大小。 2、Mono.Xml 用例 編譯日誌可以觀測到沒有引用System.Xml.dll(該文件約1mb) 3、Syste ...
  • 1.VisualStudio2017設置版權 a 在團隊開發或者公司開發中,我們一般都喜歡給自己所創建的類或者介面以及其它模板設置版權說明,但是每個類一個一個的去加又是非常的費勁,所以一般情況下我們都是設置模板來實現它,當您在VS中創建類或者介面等的時候自動將這些註釋添加到您所在的類或者介面中。 b ...
  • 項目中的代碼洋洋灑灑寫了很多,最近回過頭來看看,能精簡的地方太多了。WPF MVVM是個非常實用的模式。但前提是控制項需要支持。等等,還有不支持binding的控制項麽?基礎的控制項當然不在此列,然而實踐中常常會遇到需要組合的控制項,將一組控制項放在一起完成一個基本功能。還有控制項需要根據不同的情況改變顯示形式 ...
  • 緊跟上一篇文章。通過路由和動作匹配後,最終會得到跟當前請求最匹配的一個ActionDescriptor,然後通過IActionInvoker執行動作。 我們先來看一下IActionInvoker如何得到,代碼如下: 從上面的代碼可以看到,一個IActionInvoker是通過IActionInvok ...
  • 這個問題一開始覺得還是挺簡單的,網上也看到不少解決方案。 首先一個最簡單最直接的方案就是自定義一個名為FinalValue的依賴屬性。隨後重載OnThumbDragCompleted函數,在Thumb控制項完成拖動時改寫FinalValue。代碼如下 試著跑一下,似乎搞定了。等一下,左右鍵怎麼不起作用 ...
  • 原網頁 http://www.web-jia.com/view.php?a=10 今天在開發中遇到個bug 我在datatable中添加數據的時候報錯了我傳了大於int32的數字就出錯了 datatable中的用columns.add("test", SqlDbType.BigInt.GetType ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...