【asp.net】將GridView數據導出Excel

 

概要:html

   中午睡了一會,醒來的時候看到老師叫我去辦公室,需求是這樣的,把excel表中的每一個同窗,判斷圖片目錄中是否有對應的照片(圖片的名字用的學號或身份證號碼)web

沒有對應圖片的學生記錄,存入本身的數據表中或直接輸出,最後下載成Excelsql

因而回去後他把Excel和照片發給我數據庫

正文開始:app

 雖然沒接觸過Excel的數據導入和將GridView數據導出Excel,在網上查找了不少資料,最後彙總成功實現。asp.net

這是第一次寫本身的博客並與你們分享。函數

 

  

 

我也是查了百度學來的,詳細地址:佈局

http://jingyan.baidu.com/article/47a29f24003521c0142399dc.html學習

 

 

 

 

 2.將圖片目錄全部圖片對應的名稱導入另一張表(image表),圖片有些多而且如何能達到高效遍歷目錄文件,因而又去查百度了!地址以下:測試

http://blog.csdn.net/love_rrr/article/details/7779403

http://www.cnblogs.com/xdesigner/archive/2006/12/08/586177.html 

代碼以下:

#region 聲明WIN32API函數以及結構 **************************************
    [Serializable,
    System.Runtime.InteropServices.StructLayout
      (System.Runtime.InteropServices.LayoutKind.Sequential,
      CharSet = System.Runtime.InteropServices.CharSet.Auto
      ),
    System.Runtime.InteropServices.BestFitMapping(false)]
    private struct WIN32_FIND_DATA
    {
        public int dwFileAttributes;
        public int ftCreationTime_dwLowDateTime;
        public int ftCreationTime_dwHighDateTime;
        public int ftLastAccessTime_dwLowDateTime;
        public int ftLastAccessTime_dwHighDateTime;
        public int ftLastWriteTime_dwLowDateTime;
        public int ftLastWriteTime_dwHighDateTime;
        public int nFileSizeHigh;
        public int nFileSizeLow;
        public int dwReserved0;
        public int dwReserved1;
        [System.Runtime.InteropServices.MarshalAs
          (System.Runtime.InteropServices.UnmanagedType.ByValTStr,
          SizeConst = 260)]
        public string cFileName;
        [System.Runtime.InteropServices.MarshalAs
          (System.Runtime.InteropServices.UnmanagedType.ByValTStr,
          SizeConst = 14)]
        public string cAlternateFileName;
    }
    [System.Runtime.InteropServices.DllImport
      ("kernel32.dll",
      CharSet = System.Runtime.InteropServices.CharSet.Auto,
      SetLastError = true)]
    private static extern IntPtr FindFirstFile(string pFileName, ref WIN32_FIND_DATA pFindFileData);
    [System.Runtime.InteropServices.DllImport
      ("kernel32.dll",
      CharSet = System.Runtime.InteropServices.CharSet.Auto,
      SetLastError = true)]
    private static extern bool FindNextFile(IntPtr hndFindFile, ref WIN32_FIND_DATA lpFindFileData);
    [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool FindClose(IntPtr hndFindFile);   
    #endregion

    //具體方法函數

     Stack<string> m_scopes = new Stack<string>();
    private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
    WIN32_FIND_DATA FindFileData;
    private System.IntPtr hFind = INVALID_HANDLE_VALUE;
    void FindFileInDir(string rootDir)
    {
        string path = rootDir;
        start:
        new FileIOPermission(FileIOPermissionAccess.PathDiscovery, Path.Combine(path, ".")).Demand();
        if (path[path.Length - 1] != '\\')
        {
            path = path + "\\";
        }
        Response.Write("文件夾爲:"+path+"<br>");
        hFind = FindFirstFile(Path.Combine(path,"*"), ref FindFileData);
        if(hFind!=INVALID_HANDLE_VALUE)
        {
            do
            {
                if (FindFileData.cFileName.Equals(@".") || FindFileData.cFileName.Equals(@".."))
                    continue;
                if ((FindFileData.dwFileAttributes & 0x10) != 0)
                {
                    m_scopes.Push(Path.Combine(path, FindFileData.cFileName));
                }
                else
                {
                    Response.Write(FindFileData.cFileName+"<br>");
                }
            }
            while (FindNextFile(hFind, ref FindFileData));            
        }
        FindClose(hFind);
        if (m_scopes.Count > 0)
        {
            path = m_scopes.Pop();
            goto start;
        }
    }


//調用方法以下: 

FindFileInDir(@"D:\images\images"); //絕對路徑

 

 

 

 

3.(再次看了下需求)按照需求把Page2表中的每一個同窗,判斷image表中是否有對應的照片

沒有對應圖片的學生記錄,輸出到GridView,最後下載成Excel

頁面佈局

代碼以下:

<div style="width:100%">
       
    查詢條件:<asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Value="0" Text="=查詢全部="></asp:ListItem>
        <asp:ListItem Value="1" Text="=身份證ID查詢="></asp:ListItem>
        <asp:ListItem Value="2" Text="=姓名查詢="></asp:ListItem>
         </asp:DropDownList>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    &nbsp;&nbsp;&nbsp;&nbsp;<asp:Button ID="Button2" runat="server" Text="查詢" OnClick="Button2_Click" style="height: 21px" />&nbsp;&nbsp;&nbsp;&nbsp;<asp:Button ID="Button1" runat="server" Text="下載EXCEL" onclick="Button1_Click" />&nbsp;&nbsp;&nbsp;&nbsp;
        <br />
    <br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"  Width="100%" PageSize="15">
    <Columns>
    <asp:TemplateField HeaderText="序號">
    <ItemTemplate><%#Eval("RowNum") %></ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="用戶ID">
    <ItemTemplate><%#Eval("UserID") %></ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="用戶姓名">
    <ItemTemplate><%#Eval("Name") %></ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="身份證號">
    <ItemTemplate><%#Eval("PassCardID") %></ItemTemplate>
    </asp:TemplateField>
        <asp:TemplateField HeaderText="性別">
    <ItemTemplate><%#Eval("Sex") %></ItemTemplate>
    </asp:TemplateField>
        <asp:TemplateField HeaderText="學院">
    <ItemTemplate><%#Eval("College") %></ItemTemplate>
    </asp:TemplateField>

        <asp:TemplateField HeaderText="班級名稱">
    <ItemTemplate><%#Eval("ClassName") %></ItemTemplate>
    </asp:TemplateField>
        <asp:TemplateField HeaderText="年級">
    <ItemTemplate><%#Eval("ClassID") %></ItemTemplate>
    </asp:TemplateField>




    
   

    </Columns>
    </asp:GridView>
<br />
    <webdiyer:AspNetPager ID="AspNetPager1" runat="server" FirstPageText="首頁" 
        LastPageText="尾頁" NextPageText="下一頁" PrevPageText="上一頁" PageSize="20" 
        onpagechanged="AspNetPager1_PageChanged">
    </webdiyer:AspNetPager>
    <div>
        
    </div>
</div>

後臺代碼以下:

public void BindPagerPage(GridView gv, AspNetPager pager)
{
 string sql = "with  page as (select *,Row_number() OVER (ORDER BY UserID  desc)as RowNum from Page2 where not exists   (select imagename from dbo.[image] where  Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select * from page where RowNum>{0} and RowNum<{1}";

sql = string.Format(sql, (pager.CurrentPageIndex - 1) * pager.PageSize, (pager.CurrentPageIndex - 1) * pager.PageSize + pager.PageSize);
pager.RecordCount = int.Parse(new DataBase().ExecuteValue("with page as(select Count(*) as RowNum from Page2 where not exists   (select imagename from dbo.[image] where  Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select RowNum from page"));
gv.DataSource = new DataBase().GetDataTable(sql);
gv.DataBind();

}

  

由於用到了AspNetPager開源分頁控件,想在GridView上展現良好的分頁效果完成,開始編寫的數據庫語句數據出現重複,最後修改的時候數據庫語句反覆出現錯誤跟着提示,才使數據無重複效果,若是有比較好的語句能夠教下我,謝謝!(這裏由於數據重複花了很多時間)

數據確實有點多,剩下的圖片因爲太多了,在QQ上傳文件接收又慢,最後拿了老師發了我30多張圖片我作下測試。

數據獲得了良好的展現!

 

 

 

4.最後一步是最關鍵:將GridView數據導出Excel,在這裏我又用到了一個開源控件MyXls.SL2

 

protected void Button1_Click(object sender, EventArgs e)
    {	

        string strsql = " with  page as (select *,Row_number() OVER (ORDER BY UserID  asc)as RowNum from Page2 where not exists   (select imagename from dbo.[image] where  Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select * from page";
        Dal.DataBase db = new Dal.DataBase();
        ExcelDown exceldown = new ExcelDown();
        exceldown.downExcel(Response, db.GetDataTable(strsql), "page" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + DateTime.Now.Millisecond, Server.MapPath("~/Excel"));
}

  

總結:此次任務完成,而且也學到了將GridView數據導出Excel,本身是從大一下學期開始接觸C#學了一段時間後開始學習asp.net,當時什麼都不懂,老師就給我一些小案例去作,開始百度找的學習視頻都是很模糊,看的時候不多敲代碼致使後來過久不用了就忘記了,學習效率很是低,,接下來的日子裏天天都是看別人寫的博客和看一些項目案例視頻學習敲代碼而且本身把作好的小模塊、知識點整理起來等要用的時候就複製粘貼,也獲得了老師和學長的幫助,很感謝他們,寫博客就是想認識多一些人交流學習,保持學習的狀態!

完整代碼

ExcelDown.cs

namespace Dal
{
    public class ExcelDown
    {
        public void downExcel(HttpResponse response, DataTable dt, string fileName, string path)
        {
            XlsDocument xls = new XlsDocument();//新建一個
            xls.FileName = fileName + ".xls";
            Worksheet sheet = xls.Workbook.Worksheets.Add("Sheet1");
            //填充表頭
            try
            {
                foreach (DataColumn col in dt.Columns)
                {
                    sheet.Cells.Add(1, col.Ordinal + 1, col.ColumnName);
                }
                //填充內容
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        sheet.Cells.Add(i + 2, j + 1, dt.Rows[i][j].ToString());
                    }
                }


                #region
                using (MemoryStream ms = new MemoryStream())
                {
                    xls.Save(ms);
                    ms.Flush();
                    ms.Position = 0;
                    sheet = null;
                    xls = null;
                    // HttpResponse response = System.Web.HttpContext.Current.Response;
                    response.Clear();
                    response.Charset = "UTF-8";
                    response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
                    System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + fileName + ".xls"));
                    //System.Web.HttpContext.Current.Response.WriteFile(fi.FullName);
                    byte[] data = ms.ToArray();
                    System.Web.HttpContext.Current.Response.BinaryWrite(data);

                }
                #endregion
            }
            finally
            {
                sheet = null;
                xls = null;
            }
        }


    }
}

PageDal.cs

 public void BindPagerPage(GridView gv, AspNetPager pager)
        {

string sql = "with page as (select *,Row_number() OVER (ORDER BY UserID desc)as RowNum from Page2 where not exists (select imagename from dbo.[image] where Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select * from page where RowNum>{0} and RowNum<{1}";

  
            sql = string.Format(sql, (pager.CurrentPageIndex - 1) * pager.PageSize, (pager.CurrentPageIndex - 1) * pager.PageSize + pager.PageSize);

pager.RecordCount = int.Parse(new DataBase().ExecuteValue("with page as(select Count(*) as RowNum from Page2 where not exists (select imagename from dbo.[image] where Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select RowNum from page"));
gv.DataSource = new DataBase().GetDataTable(sql);
gv.DataBind();

        }


page.aspx

public partial class Page : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) { bind();

     //   FindFileInDir(@"D:\images\images"); //絕對路徑 只用一次用完記得註釋
        
        }
    }
    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        bind();
    }
    public void bind()
    {
        new PageDal().BindPagerPage(GridView1, AspNetPager1);
    }

    

    protected void Button1_Click(object sender, EventArgs e)
    {

        string strsql = " with  page as (select *,Row_number() OVER (ORDER BY UserID  asc)as RowNum from Page2 where not exists   (select imagename from dbo.[image] where  Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select * from page";
        Dal.DataBase db = new Dal.DataBase();
        ExcelDown exceldown = new ExcelDown();
        exceldown.downExcel(Response, db.GetDataTable(strsql), "Page" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + DateTime.Now.Millisecond, Server.MapPath("~/Excel"));
    }


    protected void Button2_Click(object sender, EventArgs e)
    {
   //     bind();//點擊查詢
    }






    #region 聲明WIN32API函數以及結構 **************************************
    [Serializable,
    System.Runtime.InteropServices.StructLayout
      (System.Runtime.InteropServices.LayoutKind.Sequential,
      CharSet = System.Runtime.InteropServices.CharSet.Auto
      ),
    System.Runtime.InteropServices.BestFitMapping(false)]
    private struct WIN32_FIND_DATA
    {
        public int dwFileAttributes;
        public int ftCreationTime_dwLowDateTime;
        public int ftCreationTime_dwHighDateTime;
        public int ftLastAccessTime_dwLowDateTime;
        public int ftLastAccessTime_dwHighDateTime;
        public int ftLastWriteTime_dwLowDateTime;
        public int ftLastWriteTime_dwHighDateTime;
        public int nFileSizeHigh;
        public int nFileSizeLow;
        public int dwReserved0;
        public int dwReserved1;
        [System.Runtime.InteropServices.MarshalAs
          (System.Runtime.InteropServices.UnmanagedType.ByValTStr,
          SizeConst = 260)]
        public string cFileName;
        [System.Runtime.InteropServices.MarshalAs
          (System.Runtime.InteropServices.UnmanagedType.ByValTStr,
          SizeConst = 14)]
        public string cAlternateFileName;
    }
    [System.Runtime.InteropServices.DllImport
      ("kernel32.dll",
      CharSet = System.Runtime.InteropServices.CharSet.Auto,
      SetLastError = true)]
    private static extern IntPtr FindFirstFile(string pFileName, ref WIN32_FIND_DATA pFindFileData);
    [System.Runtime.InteropServices.DllImport
      ("kernel32.dll",
      CharSet = System.Runtime.InteropServices.CharSet.Auto,
      SetLastError = true)]
    private static extern bool FindNextFile(IntPtr hndFindFile, ref WIN32_FIND_DATA lpFindFileData);
    [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool FindClose(IntPtr hndFindFile);   
    #endregion

    //具體方法函數

     Stack<string> m_scopes = new Stack<string>();
    private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
    WIN32_FIND_DATA FindFileData;
    private System.IntPtr hFind = INVALID_HANDLE_VALUE;
    void FindFileInDir(string rootDir)
    {
        string path = rootDir;
        start:
        new FileIOPermission(FileIOPermissionAccess.PathDiscovery, Path.Combine(path, ".")).Demand();
        if (path[path.Length - 1] != '\\')
        {
            path = path + "\\";
        }
        Response.Write("文件夾爲:"+path+"<br>");
        hFind = FindFirstFile(Path.Combine(path,"*"), ref FindFileData);
        if(hFind!=INVALID_HANDLE_VALUE)
        {
            do
            {
                if (FindFileData.cFileName.Equals(@".") || FindFileData.cFileName.Equals(@".."))
                    continue;
                if ((FindFileData.dwFileAttributes & 0x10) != 0)
                {
                    m_scopes.Push(Path.Combine(path, FindFileData.cFileName));
                }
                else
                {
                    Response.Write(FindFileData.cFileName+"<br>");
                    string[] str =FindFileData.cFileName.Split('.');
                    DataBase db = new DataBase();
                    string comstr = "insert into Image(imageName) values(@ImageName)";
                    SqlParameter[] param = new SqlParameter[1];
                    param[0] = new SqlParameter("@ImageName", SqlDbType.VarChar, 256);
                    param[0].Value = str[0];
                    db.ExecuteSql(comstr, param);
                }
            }
            while (FindNextFile(hFind, ref FindFileData));            
        }
        FindClose(hFind);
        if (m_scopes.Count > 0)
        {
            path = m_scopes.Pop();
            goto start;
        }
    }




}
       
相關文章
相關標籤/搜索