欢迎来到.net学习网

欢迎联系站长一起更新本网站!QQ:879621940

您当前所在位置:首页 » C# » 正文

热门阅读

使用OleDb,让Excel操作与数据库一样简单。

创建时间:2011年07月13日 17:11  阅读次数:(20971)
分享到:

以下代码,基本包括了对Excel的所有基础操作
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;
using System.Windows.Forms;
using System.Threading;

namespace GuideInto
{
    public class DAL_File
    {
        public static string FilePath
        {
            get;
            set;
        }

        /// <summary>
        /// 连接Excel
        /// </summary>
        /// <returns></returns>
        public static OleDbConnection Conn()
        {
            string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=True;Data Source=" + FilePath + ";Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(connStr);

            return conn;
        }

        /// <summary>
        /// 读取所有工作薄
        /// </summary>
        /// <returns></returns>
        public static DataTable GetAllExeclWorkBook()
        {
            using (OleDbConnection conn = Conn())
            {
                conn.Open();
                DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                return dt;
            }
        }

        /// <summary>
        /// 根据Sql读取Excel中的数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataSet Query(string sql)
        {
            using (OleDbConnection conn = Conn())
            {
                conn.Open();
                OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
                DataSet ds = new DataSet();
                da.Fill(ds, "ds");
                return ds;
            }
        }

        /// <summary>
        /// 读取指定工作薄中的数据
        /// </summary>
        /// <param name="sheetname"></param>
        /// <returns></returns>
        public static DataTable GetList(string sheetname)
        {
            string sql = "select * from [" + sheetname + "]";

            return Query(sql).Tables[0];
        }

        /// <summary>
        /// 判断表指定工作薄是否存在
        /// </summary>
        /// <param name="sheetname"></param>
        /// <returns></returns>
        public static bool Exists(string sheetname)
        {
            try
            {
                string sql = "select top 1 * from [" + sheetname + "]";

                Query(sql);
                return true;
            }
            catch (OleDbException ex)
            {
                if (ex.Message.Contains("不存在"))
                    return false;
            }
            return false;
        }

        /// <summary>
        /// 删除execl中指定工作薄
        /// </summary>
        /// <param name="sheetname"></param>
        public static void DropSheet(string sheetname)
        {
            using (OleDbConnection conn = Conn())
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    conn.Open();
                    cmd.Connection = conn;
                    cmd.CommandText = "drop table " + sheetname;
                    cmd.CommandType = CommandType.Text;

                    cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// 插入数据到工作薄
        /// </summary>
        /// <param name="dt"></param>
        public static void AddDateToSheet(DataTable dt, ProgressBar bar, Label lb)
        {
            using (OleDbConnection conn = Conn())
            {
                conn.Open();
                using (OleDbTransaction trans = conn.BeginTransaction())
                {
                    try
                    {

                        OleDbCommand cmd = new OleDbCommand();
                        StringBuilder strSql;
                        if (dt.Rows.Count > 1)
                        {
                            bar.Minimum = 1;
                            bar.Maximum = dt.Rows.Count;
                            lb.Visible = bar.Visible = true;
                        }
                        for (int j = 0; j < dt.Rows.Count; j++)
                        {
                            if (j <= bar.Maximum)
                            {
                                bar.Value = j + 1;
                                lb.Text = (bar.Value * 100 / bar.Maximum).ToString() + "%";
                            }
                            Application.DoEvents();

                            cmd.Transaction = trans;
                            cmd.Connection = conn;
                            cmd.CommandType = CommandType.Text;

                            strSql = new StringBuilder();
                            strSql.Append("insert into " + dt.TableName + "(");

                            for (int i = 0; i < dt.Columns.Count; i++)
                            {
                                if (i != dt.Columns.Count - 1)
                                    strSql.Append("[" + dt.Columns[i].ColumnName + "],");
                                else
                                    strSql.Append("[" + dt.Columns[i].ColumnName + "]");
                            }

                            strSql.Append(") values (");
                            string value;
                            for (int i = 0; i < dt.Columns.Count; i++)
                            {
                                value = dt.Rows[j][i].ToString() == "" ? "null" : dt.Rows[j][i].ToString();
                                if (!string.IsNullOrEmpty(value))
                                {
                                    value = value.Replace("'", "''");
                                }

                                if (GetSheetTypeByInt(dt.Columns[i].DataType.Name) && i != dt.Columns.Count - 1 && value.Equals("null"))
                                    strSql.Append(value + ",");
                                else if (GetSheetTypeByInt(dt.Columns[i].DataType.Name) && i == dt.Columns.Count - 1 && value.Equals("null"))
                                    strSql.Append(value);
                                else if (GetSheetTypeByInt(dt.Columns[i].DataType.Name) && i != dt.Columns.Count - 1)
                                    strSql.Append("'" + value + "',");
                                else if (GetSheetTypeByInt(dt.Columns[i].DataType.Name) && i == dt.Columns.Count - 1)
                                    strSql.Append("'" + value + "'");
                                else if (!GetSheetTypeByInt(dt.Columns[i].DataType.Name) && i != dt.Columns.Count - 1)
                                    strSql.Append(value + ",");
                                else if (!GetSheetTypeByInt(dt.Columns[i].DataType.Name) && i == dt.Columns.Count - 1)
                                    strSql.Append(value);
                            }
                            strSql.Append(")");

                            cmd.CommandText = strSql.ToString();
                            cmd.ExecuteNonQuery();
                        }
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        //创建Execl工作薄
        public static void CreateExecl(DataTable dt)
        {
            using (OleDbConnection conn = Conn())
            {
                conn.Open();

                using (OleDbCommand cmd = new OleDbCommand())
                {
                    StringBuilder strSql = new StringBuilder();
                    strSql.Append("create table " + dt.TableName + "(");

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        if (i == dt.Columns.Count - 1)
                            strSql.Append("[" + dt.Columns[i].ColumnName + "] " + ReturnExeclType(dt.Columns[i].DataType.Name) + " null");
                        else

                            strSql.Append("[" + dt.Columns[i].ColumnName + "] " + ReturnExeclType(dt.Columns[i].DataType.Name) + " null,");
                    }
                    strSql.Append(")");

                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = strSql.ToString();
                    cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// Net数据类型与Excel中的数据类型转换
        /// </summary>
        /// <param name="SqlType"></param>
        /// <returns></returns>
        private static string ReturnExeclType(string SqlType)
        {
            switch (SqlType.ToLower())
            {
                case "string":
                    //case "smalldatetime":
                    //case "datetime":
                    return "nvarchar(255)";
                case "byte":
                    return "byte";
                case "int32":
                    return "int";
                case "decimal":
                    return "numeric";
                case "tinyint":
                    return "byte";
                case "smalldatetime":
                    return "datetime";
                case "boolean":
                    return "bit";
                default:
                    return SqlType;
            }
        }

        /// <summary>
        /// Excel中的数据类型与Net数据类型转换
        /// </summary>
        /// <param name="SqlType"></param>
        /// <returns></returns>
        private static bool GetSheetTypeByInt(string sheettype)
        {
            switch (sheettype.ToLower())
            {
                case "string":
                    return true;
                case "smalldatetime":
                    return true;
                case "datetime":
                    return true;
                default:
                    return false;
            }
        }
    }
}

 

来源:.net学习网
说明:所有来源为 .net学习网的文章均为原创,如有转载,请在转载处标注本页地址,谢谢!
【编辑:Wyf

打赏

取消

感谢您的支持,我会做的更好!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

最新评论

共有评论4条
  • #1楼  评论人:lafong  评论时间:2011-12-9 11:26:53
  • thank you very much
  • #2楼  评论人:Wyf  评论时间:2011-12-13 13:53:24
  • 呵呵,一起进步。
  • #3楼  评论人:man  评论时间:2015-4-14 16:41:01
  • thank you
  • #4楼  评论人:wyf  评论时间:2015-4-15 17:17:03
  • no thank
发表评论:
留言人:
内  容:
请输入问题 68+18=? 的结果(结果是:86)
结  果: