C#鏈接Excel讀取與寫入數據庫SQL ( 下 )

接上期html

dataset簡而言之能夠理解爲 虛擬的 數據庫或是Excel文件。而dataset裏的datatable 能夠理解爲數據庫中的table活着Excel裏的sheet(Excel裏面不是能夠新建不少表嗎)。sql

這樣說應該很容易懂了,至關於dataset只是暫時存放下數據,微軟官方解釋是存在內存中。至於爲啥要找個「中介」來存數據,這個估計是爲了和SQL匹配。數據庫

 

好了,接下來講下此次的重點。服務器

在把Excel的數據存到dataset後,咱們要把dataset的數據存入SQL纔算完事。app

廢話很少說先上後面的代碼:(總的代碼)ide

using System.IO;
using System.Data;
using System.Configuration;
using System.ServiceProcess;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Timers;using System;

namespace DataCollection_model_HD
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {

            InitializeComponent();
            InitTimer();
        }
        #region 各類配置的全局定義
        //定義一個dataset 用於暫時存放excel中的數據,後續要存入datatable
        DataSet ds = new DataSet();
        Timer TimModel = new Timer();

        public static string LogPath = ConfigurationManager.AppSettings["LogPath"].ToString();
        public static string WPath = ConfigurationManager.AppSettings["WorkingPath"].ToString();
        public static string APath = ConfigurationManager.AppSettings["ArchivePath"].ToString();
        //數據庫登陸
        //注意Integrated Security不寫(false)表示必需要用pwd登陸,true表示不用密碼也能進入數據庫
        public static string ConnStr = ConfigurationManager.AppSettings["ConnStr"].ToString();
        //用於記錄log的時候,機臺名字
        public static string machineName = "test";
        #endregion
        #region 定時器的初始化,及其事務
        //這個按鈕用於模擬服務(定時器)啓動
        public void InitTimer()
        {
            //DFL的定時器 
            TimModel.Interval = 15 * 1000;
            //定時器的事務
            TimModel.Elapsed += new ElapsedEventHandler(ElapsedEventDFL);
            TimModel.Enabled = true;
            TimModel.AutoReset = true;
        }
        private void ElapsedEventDFL(object source, ElapsedEventArgs e)
        {
            
            if (GetFiles("test"))
            {
                //屢次讀取數據,存在多個文件時但其中某個文件在使用的bug
                ds.Tables.Clear();
                Log4App.WriteLine(" ---- End the collect ! ----", LogPath, machineName, System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), Log4AES.Type.Information);
            }
            else
            {
                DataToSql("test");
                BackupData("test");
                Log4App.WriteLine(" ---- End the collect ! ----", LogPath, machineName, System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), Log4AES.Type.Information);
            }
            
        }
        #endregion
        //log初始化設置
        Log4Application Log4App = new Log4Application();

        /*用於移動源文件到指定文件夾,也就是備份源數據文件
        copy all file in folder Working to Achieve*/
        public void BackupData(string equipName)
        {
            //須要存放(備份)的文件夾路徑(Achieve)
            string ArchivePath = APath + equipName + " Equipment Temp. monitoring by third tool\\Archive";
            //讀取數據源文件的文件夾路徑(Working)
            string WorkingPath = WPath + equipName + " Equipment Temp. monitoring by third tool\\Working";
            //初始化system.IO的配置(路徑)
            DirectoryInfo directoryInfo = new DirectoryInfo(WorkingPath);
            //用文件流來獲取文件夾中全部文件,存放到
            FileInfo[] files = directoryInfo.GetFiles();
            //循環的把全部機臺數據備份到Achieve文件夾
            try
            {
                foreach (FileInfo file in files) // Directory.GetFiles(srcFolder)
                {
                    //使用IO中的Moveto函數進行移動文件操做
                    file.MoveTo(Path.Combine(ArchivePath, file.Name));


                }
            }
            catch (Exception ex)
            {

            }
        }
        //判斷Excel是否在被人使用
        public bool IsUsed(String fileName)
        {
            bool result = false;

            try
            {
                FileStream fs = File.OpenWrite(fileName);
                fs.Close();
            }
            catch
            {
                result = true;
            }
            return result;
        }

        //將xls文件投入datatable , 返回一個datatable爲 ds.table[0]
        public bool GetFiles(string equipName)
        {
            bool flag = false;
            //choose all sheet?  or all data in sheet?
            string strExcel = "select * from [Sheet1$]";
            //初始化system.IO的配置(路徑)
            DirectoryInfo directoryInfo1 = new DirectoryInfo(WPath + equipName + " Equipment Temp. monitoring by third tool\\Working");
            //用文件流來獲取文件夾中全部文件,存放到
            FileInfo[] files1 = directoryInfo1.GetFiles();
            foreach (FileInfo file in files1) // Directory.GetFiles(srcFolder)
            {
                // 鏈接到excel 數據源,   xlsx要用ACE
                string strConn = ("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source= " + file.FullName + "; Extended Properties='Excel 12.0';");
                OleDbConnection OledbConn = new OleDbConnection(strConn);
                if (IsUsed(file.FullName))
                {
                    flag = IsUsed(file.FullName);

                    continue;
                }
                try
                {
                    OledbConn.Open();
                    // 存入datatable,Excel表示哪個sheet,conn表示鏈接哪個Excel文件(jet、ACE)
                    OleDbDataAdapter dAdapter = new OleDbDataAdapter(strExcel, strConn);
                    dAdapter.Fill(ds);
                    OledbConn.Dispose();
                    OledbConn.Close();

                }
                catch (Exception ex)
                {

                }
            }
            return flag;
        }

        // 將datatable中的數據存入SQL server
        public void DataToSql(string equipName)
        {
            //初始化配置 sqlserver的服務器名用戶等

            SqlConnection Conn = new SqlConnection(ConnStr);
            Conn.Open();

            //配置SQLBulkCopy方法,真正用於複製數據到數據庫的方法
            SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnStr, SqlBulkCopyOptions.UseInternalTransaction)
            {
                DestinationTableName = "ModelTest_HD"
            };
            try
            {
                foreach (DataColumn item in ds.Tables[0].Columns)
                {
                    //只複製所選的相關列
                    bulkCopy.ColumnMappings.Add(item.ColumnName, item.ColumnName);
                }
                //開始複製到sql,每次在數據庫中添加
                bulkCopy.WriteToServer(ds.Tables[0]);
                bulkCopy.Close();
                //copy完了,要清空ds的內容,否則會引發循環寫入上一個內容
                ds.Tables.Clear();

            }
            catch (Exception ex)
            {

            }
            finally
            {
                //關閉數據庫通道
                Conn.Close();
            }
        }

        protected override void OnStart(string[] args)
        {
            //啓動服務時作的事情

        }
        protected override void OnStop()
        {
            //中止服務時作的事情

        }
    }
}

認真看註釋能夠看出本程序的邏輯就是:函數

一、讀取到Excel數據sqlserver

二、存Excel數據到SQL server學習

三、備份Excel文件到另外一個文件夾ui

其中一些功能你們能夠看一看,註釋也寫的很清楚。對於初學者 configurationmanager的內容是在 app.config中設置的,這裏直接去配置就行(相似html)

    不 懂能夠評論問樓主。

 

  接下來就是重要的SQLBulkCopy了:

   

foreach (DataColumn item in ds.Tables[0].Columns)
{
//只複製所選的相關列
bulkCopy.ColumnMappings.Add(item.ColumnName, item.ColumnName);
}

注意這一段代碼,表示只複製數據庫與Excel表中  「列名」一致的數據,若是不一致就不復制。(注意數據的格式,int還char 這些必須弄清楚

而後bulkCopy.WriteToServer(ds.Tables[0])這裏,就是把ds.tables的數據複製到SQLserver ,Tables[0]表示ds第一張表(其實咱們也只有一張表,至於怎麼在dataset中新建table本身能夠查查資料)

最後的最後,注意釋放這些dataset,或者table。而後通道也記得close一下。

祝你們學習快樂。

相關文章
相關標籤/搜索