.net 自己写的操作Excel 导入导出 类(以供大家参考和自己查阅)

由于现在网页很多都关系到Excel 的操作问题,其中数据的导入导出更是频繁,作为一个菜鸟,收集网上零散的知识,自己整合,写了一个Excel导入到GridView ,以及将GridView的数据导出到EXCEL的类方法,以供参考和方便自己以后查阅。

  1 #region 引用部分
  2 using System;
  3 using System.Collections.Generic;
  4 using System.Linq;
  5 using System.Web;
  6 using System.Data;
  7 using System.Data.OleDb;
  8 using System.IO;
  9 #endregion
 10 /// <summary>
 11 ///Excel_DataAcess 的摘要说明
 12 /// </summary>
 13 public class Excel_DataAcess
 14 {
 15     private string errors;
 16
 17     /// <summary>
 18     /// 获取方法错误提示
 19     /// </summary>
 20     public string Get_errors {
 21         get {
 22             return errors;
 23         }
 24     }
 25
 26     /// <summary>
 27     /// 由于版本问题,OIEDB的连接参数会有不同,所以这个字段如果拓展写,方便存储当下文件的OLEDB 的连接;
 28     /// </summary>
 29     private OleDbConnection strconnect = null;
 30
 31     /// <summary>
 32     /// 构造函数
 33     /// </summary>
 34     public Excel_DataAcess()
 35     {
 36         //
 37         //TODO: 在此处添加构造函数逻辑
 38         //
 39     }
 40
 41     /// <summary>
 42     /// 获取OLEDB的连接
 43     /// </summary>
 44     /// <param name="_path">EXCEL文件路径</param>
 45     /// <param name="flag">用于判断版本,07以下或07以上有不同的连接参数</param>
 46     /// <returns></returns>
 47     private OleDbConnection Get_Connect(string _path, int flag)
 48     {
 49         string connect;
 50         if (flag <= 7)
 51         {
 52             connect = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + _path + ";Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1‘;";
 53         }
 54         else
 55         {
 56             connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _path + ";Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1‘;";
 57         }
 58         OleDbConnection _con = new OleDbConnection(connect);
 59         return _con;
 60
 61     }
 62
 63     /// <summary>
 64     /// 导入EXCEL数据到GRIDVIEW中
 65     /// </summary>
 66     /// <param name="_path">文件路径</param>
 67     /// <param name="dt">导入的数据表</param>
 68     /// <returns>返回成功与否</returns>
 69     public bool ReportExce(string _path, out DataTable dt)
 70     {
 71
 72         bool result = false;
 73         dt = null;
 74
 75         try
 76         {
 77             OleDbConnection _con = Get_Connect(_path, 8);
 78             try
 79             {
 80                 _con.Open();
 81             }
 82             catch {
 83                 _con = Get_Connect(_path, 7);
 84                 _con.Open();
 85             }
 86             Dictionary<int,string> test= Get_Sheet(_con);
 87
 88             string sql = string.Format("select * from [{0}]", test[0]);
 89
 90             OleDbDataAdapter _date = new OleDbDataAdapter(sql, _con);
 91             DataSet _set = new DataSet();
 92             _date.Fill(_set, "table");
 93             dt = _set.Tables[0];
 94             _con.Close();
 95             result = true;
 96             strconnect = _con;
 97         }
 98         catch(Exception ex) {
 99             string err = ex.Message;
100         }
101
102         return result;
103
104
105     }
106
107     /// <summary>
108     /// 获取当前EXCEL文件的所有SHEET
109     /// </summary>
110     /// <param name="_con">当前连接</param>
111     /// <returns>返回一个集合</returns>
112     public Dictionary<int, string> Get_Sheet(OleDbConnection _con)
113     {
114         Dictionary<int, string> Allsheet = new Dictionary<int, string>();
115
116         DataTable dt = _con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
117
118         for (int i = 0; i < dt.Rows.Count;i++ ) {
119             Allsheet.Add(i, dt.Rows[i][2].ToString());
120         }
121
122         return Allsheet;
123     }
124
125     /// <summary>
126     /// 导出GRIDVIEW数据到EXCEL文件中
127     /// </summary>
128     /// <param name="obj">传入的GRIDVIEW控件</param>
129     /// <returns>返回成功与否</returns>
130     public bool OutExcel(object obj) {
131         System.Web.UI.WebControls.GridView gid = (System.Web.UI.WebControls.GridView)obj;
132
133         bool result = false;
134
135         //string style = "";
136         //if (gid.Rows.Count > 0) {
137         //    [email protected]"<style> .text { mso-number-format:\@; } </script> ";
138         //}
139         try
140         {
141             string filename = DateTime.Now.ToString();
142
143             HttpContext.Current.Response.ClearContent();
144
145             HttpContext.Current.Response.Buffer = true;
146             //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
147             HttpContext.Current.Response.Charset = "GB2312";
148             //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
149             HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
150             //Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
151             //Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
152             HttpContext.Current.Response.AddHeader("Content-disposition", "attachment;filename=" + filename + ".xls");
153             //Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
154             HttpContext.Current.Response.ContentType = "application/excel";
155             //StreamWriter sw = new StreamWriter();
156             StringWriter sw = new StringWriter();
157             System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
158             gid.RenderControl(htw);
159             HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=gb2312\"/>"+sw.ToString());
160
161             result = true;
162         }
163         catch (Exception ex)
164         {
165             errors = ex.Message;
166         }
167         finally {
168             HttpContext.Current.Response.End();
169         }
170         return result;
171
172     }
173 }
时间: 2024-08-01 22:47:11

.net 自己写的操作Excel 导入导出 类(以供大家参考和自己查阅)的相关文章

c#操作excel导入导出时同时向用户表插入账户与密码

<><><><>本代码源于师兄<><><><><><> 1:首先需要在前端显示界面View视图中添加导入Excel和导出Excel按钮: @using (Html.BeginForm()) { } 这里注意,导出Excel是通过获取当下的表单的方式来导出数据的. 2:然后为导入Excel添加导入方法function: js部分以图片存放 3:添加点击事件后弹出来的操作界面(importe

不依赖Excel是否安装的Excel导入导出类

本文利用第三方开源库NPOI实现Excel97-2003,Excel2007+的数据导入导出操作. 不依赖Office是否安装.NPOI开源项目地址:http://npoi.codeplex.com/. 库文件下载:http://npoi.codeplex.com/releases/view/115353 using System; using System.Collections; using System.Collections.Generic; using System.Data; usi

【原创】POI操作Excel导入导出工具类ExcelUtil

关于本类线程安全性的解释: 多数工具方法不涉及共享变量问题,至于添加合并单元格方法addMergeArea,使用ThreadLocal变量存储合并数据,ThreadLocal内部借用Thread.ThreadLocalMap以当前ThreadLocal为key进行存储,设置一次变量,则其他线程也会有上次数据的残留,因此在addMergeArea方法中进行清空的操作.为了保证原子性, 采用ReentrantLock确保一次只有一个线程可以进行添加合并数据的操作. 线程安全性从以上两个方面保证. 水

NOPI操作EXCEL导入导出

private void btnOutput_Click(object sender, EventArgs e) { List<MODEL.Classes> list = cm.GetClassInfo(false); //获取对象数据集合 HSSFWorkbook workbook=new HSSFWorkbook (); //新建Excel工作表 HSSFSheet sheet=workbook.CreateSheet("classes"); //在工作文档中新建页 f

excel导入导出优化

对于上一篇excel中出现的问题,在excel导入导出中都做了优化.还是eclipse+jdk1.8,但是这个项目是一个web项目,需要配合Tomcat服务器,并且使用了SSH框架, I/O操作过多 首先,对于I/O操作过多,那么就不像之前一样,一条一条的添加或者更新;而且凑齐一堆,也就是一个list集合,然后统一的批量保存. 使用SessionFactory获取当前的session,然后调用session的persist方法,保存实体.只是设置了一个批量的量值.每到30条数据,就将缓存同步到数

Excel导入导出帮助类

/// <summary>    /// Excel导入导出帮助类    /// 记得引入 NPOI    /// 下载地址   http://npoi.codeplex.com/releases/    /// </summary> public class ExcelHelper    {        #region 导出Excel /// <summary>        /// 导出Excel  注:model 字段必须加[DisplayName("

java jxl excel 导入导出的 总结(建立超链接,以及目录sheet的索引)

最近项目要一个批量导出功能,而且要生成一个单独的sheet页,最后后面所有sheet的索引,并且可以点击进入连接.网上搜索了一下,找到一个方法,同时把相关的excel导入导出操作记录一下!以便以后使用! 简单先写一下目录的建立的主要代码,测试用的 List ls = new ArrayList();//报表名称列表  ls.add("BB_BB03");  ls.add("BB_BB05");  ls.add("BB_BB06"); try { 

Mego(04) - NET简单实现EXCEL导入导出

前言 相信做过信息系统的朋友都会遇到EXCEL导入导出的相关开发,做过不少EXCEL导入导出后总结起来大致有如下几种方式实现: ADO.NET的OldDb或ODBC连接EXCEL使用DataTable来读取数据. Microsoft.Office.Interop.Excel用微软提供的组件操作WorkSheet对象. 使用一些第三方的库比如Fast Excel.ExcelDataReader等等. 今天要向大家介绍的更简单的方式来实现日常开发的各种EXCEL导入导出需求. 简单导入 我们还是使用

Excel导入导出的业务进化场景及组件化的设计方案(转)

1:前言 看过我文章的网友们都知道,通常前言都是我用来打酱油扯点闲情的. 自从写了上面一篇文章之后,领导就找我谈话了,怕我有什么想不开. 所以上一篇的(下)篇,目前先不出来了,哪天我异地二次回忆的时候,再分享分享. 话说最近外面IT行情飞涨还咋的,人都飞哪去了呢,听说各地的军情都进入紧急状态了. 回归下正题,今天就抽点时间,写写技术文,和大伙分享一下近年在框架设计上的取的一些技术成果. 2:项目背景 在针对运营商(移动.联通.电信.铁塔)的信息类的系统中,由于相关的从业人员习惯于Excel的办公