使用Excel下载数据库里的数据

今天我们来看看用Excel下载指定数据库里面的数据。

所用软件:
Microsoft Visual Studio 2010
SQL Server Management Studio

首先,我们要建立一个数据库,本例以Table_4来讲解。
Table_4:
在这里插入图片描述
建立好了以后,在VS里面建立三层。不会的参考以前讲过的:https://my.oschina.net/u/3913001/blog/1858562

结构代码如下:

Model层(userlist):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    public class userlist
    {
        public string id { get; set; }
        public string username { get; set; }
        public string userpwd { get; set; }
        public string realname { get; set; }
        public string iphone { get; set; }
        public string flge { get; set; }

    }

}

先在Model里面实例化对象。

DAL层(diaoyong):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DAL
{
    public class diaoyong
    {
        public DataSet Tabl(string where)   
     {
         DataSet ds = DB.ToGetData("select *from Table_4" + where);
         if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
         {
             return ds;
         }
         else 
         {
             return null;
         }
     
     }
    
    public class DB
        {
            static string ConnStr = "Data Source=.;Initial Catalog=调用的数据库名;Persist Security Info=True;User ID=数据库用户名;Password=数据库密码";

            public static DataSet ToGetData(string Sql)
            {
                using (SqlConnection Conn = new SqlConnection(ConnStr))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter(Sql, Conn))
                    {
                        DataSet ds = new DataSet();
                        Conn.Open();
                        da.Fill(ds);
                        da.Dispose();
                        return ds;
                    }
                }
            }
         }



    }
}

在DAL里面返回SQL里面的数据。

BLL(diaofang)层:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace BLL
{
    public class diaofang
    {
        DAL.diaoyong MyTestDal = new DAL.diaoyong();


        public DataSet Tabl(string where)   
        
        {
            return MyTestDal.Tabl("");

        }
        


    }
}



BLL层写入功能。

UI层(前端):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddUserList.aspx.cs" Inherits="三层.AddUserList" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:Button ID="Button1" runat="server" Text="下载文件" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

前端加入一个按钮,后端调用方法。

UI层(后端):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Data;
using System.IO;

namespace 三层
{
    public partial class AddUserList : System.Web.UI.Page
    {
        BLL.diaofang MyTestBll = new BLL.diaofang();
        protected void Button1_Click(object sender, EventArgs e)
        {
            string filePath = @"E:\Excel\" + DateTime.Now.ToFileTime() + ".xls";
            DataSetToExcel(MyTestBll.Tabl(""), filePath);


            //以字符流的形式下载文件
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode("downexcel.xls", System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            
        }
         public void DataSetToExcel(DataSet ds, string FileName)
        {
            try
            {



                FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
                StreamWriter sfw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("gb2312"));
  
                //变量定义 



                //定义表对象与行对象,同时用DataSet对其值进行初始化 
                System.Data.DataTable dt = ds.Tables[0];
                DataRow[] myRow = dt.Select();
               
                int cl = dt.Columns.Count;

                string TableHtml = "";
                string TableHead = "用户编号,用户名,密码,真实姓名,手机号,状态";
                string TableTr = "";
                string TableTD = "";
                
                foreach (string item in TableHead.Split(','))
                {
                    TableTD = TableTD + "<td>" + item + "</td>";
                }
                TableTr = TableTr + "<tr>" + TableTD + "</tr>";
                //sfw.WriteLine();


                //sfw.WriteLine(colHeaders);

                //逐行处理数据 
                foreach (DataRow row in myRow)
                {
                    TableTD = "";
                    //当前数据写入 
                    for (int i = 0; i < cl; i++)
                    {
                        if (IsNumeric(row[i].ToString()))
                        {
                            TableTD = TableTD + "<td>'" + row[i].ToString() + "</td>";
                        }
                        else
                        {
                            TableTD = TableTD + "<td>" + row[i].ToString() + "</td>";
                        }


                    }
                    TableTr = TableTr + "<tr>" + TableTD + "</tr>";
                }


                string stylecss = "<style type='text/css'> ";

                stylecss = stylecss + " table.gridtable { ";
                stylecss = stylecss + " font-family: verdana,arial,sans-serif; ";
                stylecss = stylecss + " font-size:20px; ";
                stylecss = stylecss + " color:#333333; ";
                stylecss = stylecss + " border-width: 1px; ";
                stylecss = stylecss + "  border-color: #666666; ";
                stylecss = stylecss + " border-collapse: collapse; ";
                stylecss = stylecss + "  } ";
                stylecss = stylecss + "  table.gridtable th { ";
                stylecss = stylecss + "   border-width: 1px; ";
                stylecss = stylecss + "    padding: 8px; ";
                stylecss = stylecss + "     border-style: solid; ";
                stylecss = stylecss + "    border-color: #666666; ";
                stylecss = stylecss + "     background-color: #dedede; ";
                stylecss = stylecss + " } ";
                stylecss = stylecss + "  table.gridtable td { ";
                stylecss = stylecss + "      border-width: 1px; ";
                stylecss = stylecss + "      padding: 8px; ";
                stylecss = stylecss + "      border-style: solid; ";
                stylecss = stylecss + "      border-color: #666666; ";
                stylecss = stylecss + "     background-color: #ffffff; ";
                stylecss = stylecss + "  } </style>";


                TableHtml = stylecss + "<table class='gridtable'>" + TableTr + "</table>";
                sfw.Write(TableHtml);

                sfw.Close();



            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public static bool IsNumeric(string value)
        {
            return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
        }
    }

    }

string filePath = @“E:\Excel” + DateTime.Now.ToFileTime() + “.xls”;注意这一句话,需要在E盘下建立一个Excel文件夹,后面可以在里面找到Excel文件。地址也可以自己更改。

后端将数据一条条写入Excel里面,并存入指定位置。

成功以后是这个状态:
在这里插入图片描述
在文件夹里面自动命名
在这里插入图片描述
怎么样?会了吗?

猜你喜欢

转载自blog.csdn.net/weixin_44003632/article/details/86630667