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


接上期

dataset簡而言之可以理解為 虛擬的 數據庫或是Excel文件。而dataset里的datatable 可以理解為數據庫中的table活着Excel里的sheet(Excel里面不是可以新建很多表嗎)。

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

 

好了,接下來說下這次的重點。

在把Excel的數據存到dataset后,我們要把dataset的數據存入SQL才算完事。

廢話不多說先上后面的代碼:(總的代碼)

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()
        {
            //停止服務時做的事情

        }
    }
}

認真看注釋可以看出本程序的邏輯就是:

1、讀取到Excel數據

2、存Excel數據到SQL server

3、備份Excel文件到另一個文件夾

其中一些功能大家可以看一看,注釋也寫的很清楚。對於初學者 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一下。

祝大家學習快樂。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM