ASP.NET Excel 文件导入与导出实例

话不多说直接来干货。。。。

连接类 Excel 通过 OleDb 类进行操作。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Data.OleDb;
 6 
 7 /// 
 8 /// ExcelHelper 的摘要说明
 9 /// 
10 public class ExcelHelper
11 {
12     private OleDbConnection conn;
13     private string connStr = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes'";
14     public ExcelHelper(string fileName)
15     {
16         connStr = string.Format(connStr, fileName);//操作的文件路径早调用对象时给定
17         Conn = new OleDbConnection(connStr);
18     }
19 
20     public OleDbConnection Conn
21     {
22         get
23         {
24             return conn;
25         }
26 
27         set
28         {
29             conn = value;
30         }
31     }
32 }
ExcelHelper
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using MySql.Data.MySqlClient;
 6 /// 
 7 /// MysqlHelper 的摘要说明
 8 /// 
 9 public class MysqlHelper
10 {
11     private MySqlConnection conn;
12     private string connection = "Data Source = 127.0.0.1;User ID = root;Password=123;Database=students;Charset=utf8";
13     public MysqlHelper()
14     {
15         Conn = new MySqlConnection(connection);      
16     }
17 
18     public MySqlConnection Conn
19     {
20         get
21         {
22             return conn;
23         }
24 
25         set
26         {
27             conn = value;
28         }
29     }
30 }
MysqlHelper

数据操作类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Data.OleDb;
 6 using System.Data;
 7 
 8 /// 
 9 /// ExcelDao 的摘要说明
10 /// 
11 public class ExcelDao
12 {
13     public ExcelDao()
14     {
15         
16     }
17     /// 
18     /// 查询 Excel 中的数据并存入数据表中
19     /// 
20     /// 连接字符串
21     /// sql命令
22     /// 返回一个数据表
23     public DataTable FindAll(OleDbConnection ocon, string sql)
24     {
25         OleDbCommand ocmd = new OleDbCommand(sql, ocon);
26         OleDbDataAdapter da = new OleDbDataAdapter(ocmd);
27         DataSet ds = new DataSet();
28         da.Fill(ds, "aa");
29         DataTable dt = ds.Tables["aa"];
30         return dt;
31     }
32     /// 
33     /// 将数据插入 Excel 中
34     /// 
35     /// sql命令
36     public void Insert(OleDbConnection coon,string sql,DataRow item,int i)
37     {
38         OleDbParameter[] pms = new OleDbParameter[3];
39         OleDbCommand ocmd = new OleDbCommand(sql, coon);
40         string id = item["学号"].ToString();
41         string name = item["姓名"].ToString();
42         string sex = item["性别"].ToString();
43 
44         pms[0] = new OleDbParameter("@a", id);
45         pms[1] = new OleDbParameter("@b", name);
46         pms[2] = new OleDbParameter("@c", sex);
47 
48         foreach(OleDbParameter iteme in pms)
49         {
50             ocmd.Parameters.Add(iteme);
51         }
52         i += ocmd.ExecuteNonQuery();
53     }
54 }
ExcelDao
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Data;
 6 using MySql.Data.MySqlClient;
 7 
 8 /// 
 9 /// MysqlDao 的摘要说明
10 /// 
11 public class MysqlDao
12 {
13     public MysqlDao()
14     {
15         //
16         // TODO: 在此处添加构造函数逻辑
17         //
18     }
19     /// 
20     /// 查询数据库中的数据并存入数据表中
21     /// 
22     /// 
23     /// 
24     /// 返回一个数据表
25     public DataTable FindAll(MySqlConnection conn,string sql)
26     {
27         MySqlCommand cmd = new MySqlCommand(sql, conn);
28         MySqlDataAdapter da = new MySqlDataAdapter(cmd);
29         DataSet ds = new DataSet();
30         da.Fill(ds, "bb");
31         DataTable dt = ds.Tables["bb"];
32         return dt;
33     }
34     /// 
35     /// 将数据表插入到数据库中
36     /// 
37     /// 
38     /// 
39     /// 
40     /// 
41     /// 
42     public int Insert(MySqlConnection conn,string sql,DataRow item,int i)
43     {
44         string id = item["学号"].ToString();
45         string name = item["姓名"].ToString();
46         string sex = item["性别"].ToString();
47         MySqlCommand cmd = new MySqlCommand(sql, conn);
48         MySqlParameter[] pm = new MySqlParameter[3];
49 
50         pm[0] = new MySqlParameter("@a", id);
51         pm[1] = new MySqlParameter("@b", name);
52         pm[2] = new MySqlParameter("@c", sex);
53 
54         foreach (MySqlParameter item1 in pm)
55         {
56             cmd.Parameters.Add(item1);
57         }
58         i += cmd.ExecuteNonQuery();
59         return i;
60     }
61     public MySqlDataReader FindAllReader(string sql,MySqlConnection conn)
62     {
63         MySqlCommand cmd = new MySqlCommand(sql, conn);
64         MySqlDataReader dr = cmd.ExecuteReader();
65         return dr;
66     }
67 }
MysqlDao

前端页面

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Excel.aspx.cs" Inherits="Excel" %>
 2 
 3 DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 8     <title>title>
 9     <style type="text/css">
10         .auto-style1 {
11             width: 100%;
12         }
13         .auto-style2 {
14             width: 372px;
15         }
16     style>
17 head>
18 <body>
19     <form id="form1" runat="server">
20     <div>
21     
22         <table class="auto-style1">
23             <tr>
24                 <td class="auto-style2">Excel文件:<asp:FileUpload ID="FileUpload1" runat="server" />
25                     <asp:Button ID="Button1" runat="server" Text="导入" OnClick="Button1_Click" />
26                 td>
27                 <td> td>
28             tr>
29             <tr>
30                 <td class="auto-style2">
31                     <asp:Button ID="Button2" runat="server" Text="预览数据库中的数据" Width="224px" OnClick="Button2_Click" />
32                     <asp:Button ID="Button3" runat="server" Text="导出" OnClick="Button3_Click" />
33                 td>
34                 <td> td>
35             tr>
36         table>
37     
38     div>
39         <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" Width="262px" ForeColor="Black" GridLines="Horizontal">
40             <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
41             <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
42             <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
43             <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
44             <SortedAscendingCellStyle BackColor="#F7F7F7" />
45             <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
46             <SortedDescendingCellStyle BackColor="#E5E5E5" />
47             <SortedDescendingHeaderStyle BackColor="#242121" />
48         asp:GridView>
49     form>
50 body>
51 html>
View Code

后台实现代码

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.UI;
  6 using System.Web.UI.WebControls;
  7 using MySql.Data.MySqlClient;
  8 using System.Data.OleDb;
  9 using System.Data;
 10 using System.IO;
 11 
 12 public partial class Excel : System.Web.UI.Page
 13 {
 14     ExcelHelper ehelper;
 15     MysqlHelper mhelper;
 16     protected void Page_Load(object sender, EventArgs e)
 17     {
 18         GridDataSource();
 19         string fileName = Server.MapPath("Down/学生.xlsx");
 20         ehelper = new ExcelHelper(fileName);
 21     }
 22     /// 
 23     /// 预览数据库中的数据
 24     /// 
 25     /// 
 26     /// 
 27     protected void Button2_Click(object sender, EventArgs e)
 28     {
 29         GridDataSource();
 30     }
 31     /// 
 32     /// 加载数据源
 33     /// 
 34     protected void GridDataSource()
 35     {
 36         mhelper = new MysqlHelper();
 37         mhelper.Conn.Open();
 38         string sql = "select * from students";
 39         MysqlDao dao = new MysqlDao();
 40         MySqlDataReader dr = dao.FindAllReader(sql, mhelper.Conn);
 41         GridView1.DataSource = dr;
 42         GridView1.DataBind();
 43         dr.Close();
 44         mhelper.Conn.Close();
 45     }
 46     /// 
 47     /// 导入
 48     /// 
 49     /// 
 50     /// 
 51     protected void Button1_Click(object sender, EventArgs e)
 52     {
 53         //1. 选择文件上传到服务器的文件夹
 54         string type = Path.GetExtension(FileUpload1.FileName);
 55         string filePath = "Down/"+FileUpload1.FileName;
 56         //fileName = filePath;
 57         FileUpload1.SaveAs(Server.MapPath(filePath));
 58 
 59         //2. 把刚上传的excel文件中的内容查询出来
 60         
 61         int i = 0;
 62         string sql = "select * from [Sheet1$]";
 63         ehelper.Conn.Open();
 64         ExcelDao dao = new ExcelDao();
 65         DataTable dt = dao.FindAll(ehelper.Conn, sql);
 66         if(dt.Equals(null)) Response.Write("dt = null");
 67         foreach(DataRow item in dt.Rows)
 68         {//将Excel中的内容存入缓存中,一条条插入mysql数据库中
 69             if (item.IsNull(0)) continue;
 70             string msql = "insert into students values(@a,@b,@c)";
 71             mhelper = new MysqlHelper();
 72             mhelper.Conn.Open();
 73             MysqlDao dao1 = new MysqlDao();
 74             i = dao1.Insert(mhelper.Conn, msql, item, i);
 75             mhelper.Conn.Close();
 76         }
 77         if (i > 1)
 78             Response.Write("导入成功");
 79         else
 80             Response.Write("导入失败");
 81         ehelper.Conn.Close();   
 82     }
 83     /// 
 84     /// 导出
 85     /// 
 86     /// 
 87     /// 
 88     protected void Button3_Click(object sender, EventArgs e)
 89     {
 90         //1. 复制一份模板
 91         string oldPath = Server.MapPath("Down/学生.xlsx");
 92         string newPath = Server.MapPath("Down/学生2.xlsx");
 93         if (System.IO.File.Exists(newPath))
 94         {
 95             System.IO.File.Delete(newPath);
 96         }
 97         System.IO.File.Copy(oldPath, newPath);
 98         //2. 查询数据表
 99         string sql = "select * from students";
100         mhelper = new MysqlHelper();
101         mhelper.Conn.Open();
102         MysqlDao dao = new MysqlDao();
103         DataTable dt = dao.FindAll(mhelper.Conn, sql);
104         // 3. 将数据插入到表格中
105         int i = 0;
106         foreach (DataRow item in dt.Rows)
107         {
108             if (item.IsNull(0)) continue;
109             string esql = "insert into [Sheet1$] values(@a,@b,@c)";
110             ehelper.Conn.Open();
111             ExcelDao dao1 = new ExcelDao();
112             dao1.Insert(ehelper.Conn, esql, item, i);
113             ehelper.Conn.Close();
114         }
115         mhelper.Conn.Close();
116         // 将数据导出到Excel文件后下载
117         Down(newPath);//下载操作
118     }
119     /// 
120     /// 下载导出的文件
121     /// 
122     /// 
123     protected void Down(string newPath)
124     {
125         Response.ContentType = "application / vnd.ms - excel";
126         Response.AddHeader("content-disposition", "attchment;filename=学生信息.xlsx");
127         FileStream fs = new FileStream(newPath, FileMode.Open, FileAccess.Read);
128         Stream st = Response.OutputStream;
129         byte[] bt = new byte[102400];//100k位单位减轻服务器压力
130         while (true)
131         {
132             int len = fs.Read(bt, 0, bt.Length);
133             if (len == 0) break;
134             st.Write(bt, 0, len);
135             Response.Flush();
136         }
137         st.Close();
138         fs.Close();
139         Response.End();
140     }
141 }
Excel

这样就可以达到对 Excel 文件导入与导出的效果了。这只是简单的实现,逻辑不完全,欢迎大家指正!

转载于:https://www.cnblogs.com/qihangzj/p/7649738.html

你可能感兴趣的:(ASP.NET Excel 文件导入与导出实例)