整理C#常见的对Excel的操作方法

1. OLEDB

这种方式将Excel作为一个数据源,直接用Sql语句获取数据了。

优点:

1) 读取速度快

2) Excel版本兼容性好

3) 运行的机器不需要安装相应的Excel

缺点:

1)对Excel单元格样式操作欠缺

2) 列类型的判断逻辑不合理,当指定了首行作为头(header)的时候,Oledb会根据该列的前若干行数据类型类判断该列的数据类型,这会导致数据丢失。例如某列前n行都为int,列的数据类型被判断为int,那么n+1行后的非可转为int的数据都会被清空。

3) Microsoft.Jet.OLEDB.4.0 不支持64位的操作系统,在64位的操作系统需要特殊处理。

4) Microsoft.ACE.OLEDB.12.0 基本是Microsoft.Jet.OLEDB.4.0的替代版本,同时提供32位和64位两个版本。

调用代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using Helper;


namespace TestProject
{
    public partial class ExcelTest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                ReadFile();
                //如果此行已有数据,就不能insert。 A10表示第11行,从0开始计算
                //DoOLEDBSql(Server.MapPath("xml/EnglishWord.xls"),"insert into [Sheet1$A10:C10](F1,F2,F3) values('111','222','333')");
                //DoOLEDBSql(Server.MapPath("xml/EnglishWord.xls"), "update [Sheet1$] set F1='yours' where F1 = 'your'"); //F1代表第一列,寻找第一列中所有值为"your"的替换
                //ExcelHelper.DoOLEDBSql(Server.MapPath("xml/EnglishWord.xls"), "update [Sheet1$] set FieldName1='yours',FieldName2='123' where FieldName1 = 'your'");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        public void ReadFile(){
            try
            {
                DataSet ds = ExcelHelper.SelectOLEDBExcel(Server.MapPath("xml/EnglishWord.xls"), "select * from [Sheet1$]");

                if (ds != null && ds.Tables.Count > 0)
                {
                    var wd = from t in ds.Tables[0].AsEnumerable()
                             where t["F1"].ToString().StartsWith("your")
                             select new
                             {
                                 Word = t["F1"].ToString(),
                                 Type = t["F2"].ToString(),
                                 Desc = t["F3"].ToString()
                             };
                    this.Repeater1.DataSource = wd;
                    this.Repeater1.DataBind();
                    
                }
            }catch(Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
}
View Code

OLEDB帮助类

#region OLEDB Operation Excel
        /// <summary>
        /// 执行OLEDB插入更新操作
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="sql"></param>
        public static void DoOLEDBSql(string filepath, string sql)
        {
            OleDbConnection conn = null;
            OleDbCommand cmd = null;
            try
            {
                conn = GetOleDBConn(filepath);
                cmd = new OleDbCommand(sql, conn);
                cmd.Connection = conn;
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                conn.Close();
            }
            catch (Exception e)
            {
                if (cmd != null)
                    cmd.Dispose();
                if (conn != null)
                    conn.Close();
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// OLEDB方式读取Excel
        /// </summary>
        /// <param name="filepath">文件绝对路径</param>
        /// <param name="sheetname">工作表名称</param>
        /// <param name="err">错误信息</param>
        /// <returns></returns>
        public static DataSet SelectOLEDBExcel(string filepath, string sql)
        {
            OleDbConnection conn = null;
            DataSet ds = null;
            try
            {
                conn = GetOleDBConn(filepath);
                OleDbCommand objCmdSelect = new OleDbCommand(sql, conn);
                OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
                objAdapter1.SelectCommand = objCmdSelect;
                ds = new DataSet();
                objAdapter1.Fill(ds);
                conn.Close();
            }
            catch (Exception e)
            {
                if (conn != null)
                    conn.Close();
                throw new Exception(e.Message);
            }
            return ds;
        }

        /// <summary>
        /// 获取OLEDB连接对象
        /// </summary>
        /// <param name="filepath">Excel文件路径</param>
        /// <returns></returns>
        public static OleDbConnection GetOleDBConn(string filepath)
        {
            OleDbConnection conn = null;
            string strConn;
            /*
            关于IMEX的值
            0 ---输出模式;
            1---输入模式;
            2----链接模式(完全更新能力)
            */
            if (filepath.EndsWith(".xls"))
            {
                strConn = string.Format("Provider=Microsoft.Jet.OLEDB.{0}.0;Data Source={1};Extended Properties='Excel {2}.0;HDR=no;IMEX=2'", "4", filepath, "8");
            }
            else
            {
                strConn = string.Format("Provider=Microsoft.Jet.OLEDB.{0}.0;Data Source={1};Extended Properties='Excel {2}.0;HDR=no;IMEX=2'", "12", filepath, "12");
            }
            conn = new OleDbConnection(strConn);
            conn.Open();
            return conn;
        }
        #endregion
View Code


2. COM方式

 这种方式需要先引用 Microsoft.Office.Interop.Excel。

优点:

1) 非常灵活的读取和操作Excel

2) 各版本的兼容性

3) 对Excel操作内容丰富

缺点

1) 运行的机器需要安装了相应版本的Excel

2)使用后不能很好的完成资源释放工作,很多时候需要通过杀掉Excel进程或者根据进程号去杀掉对应的进程来实现资源释放

3)运行速度比较低

3. NPOI

NPOI是一组开源的组件,类似Java的 POI。http://tonyqus.sinaapp.com/tutorial

优点:

1) 读取导出速度快

2) 运行机器无须安装相应版本的Excel

3) 对Excel操作内容丰富

缺点:

1) 对Excel2007控制还有许多问题

原文地址:https://www.cnblogs.com/kkwoo/p/3487673.html