C# 從Excel讀取數(shù)據(jù)向SQL server寫入
第一次寫C#與sql的東西,主要任務(wù)是從Excel讀取數(shù)據(jù),再存到SQL server中。
先上讀取Excel文件的code如下。
public bool GetFiles(string equipName) { //choose all sheet? or all data in sheet? string strExcel = "select * from [Sheet1$]"; //初始化system.IO的配置(路徑) DirectoryInfo directoryInfo1 = new DirectoryInfo(WPath + equipName + "\\Working"); //用文件流來獲取文件夾中所有文件,存放到 FileInfo[] files1 = directoryInfo1.GetFiles(); foreach (FileInfo file in files1) // Directory.GetFiles(srcFolder) { // 連接到excel 數(shù)據(jù)源, 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 OleDbDataAdapter dAdapter = new OleDbDataAdapter(strExcel, strConn); //寫入ds中的一個table dAdapter.Fill(ds); OledbConn.Dispose(); OledbConn.Close(); } catch (Exception ex) { } } }
foreach用于遍歷所有Excel文件;
strExcel用于選擇Excel文件中sheet的內(nèi)容,select * 表示選取sheet中所有行和列;
strConn用于設(shè)置讀取的方法,provider的設(shè)置很重要,ACE表示最新的.xlsx文件,jet 表示讀取.xls文件,兩者有點區(qū)別,DataSource表示文件名,包括路徑。
OleDbDataAdapter 用于按(命令)去執(zhí)行填充dataset的功能
dataset簡而言之可以理解為 虛擬的 數(shù)據(jù)庫或是Excel文件。而dataset里的datatable 可以理解為數(shù)據(jù)庫中的table活著Excel里的sheet(Excel里面不是可以新建很多表嗎)。
這樣說應(yīng)該很容易懂了,相當(dāng)于dataset只是暫時存放下數(shù)據(jù),微軟官方解釋是存在內(nèi)存中。至于為啥要找個“中介”來存數(shù)據(jù),這個估計是為了和SQL匹配。
好了,接下來說下這次的重點。
在把Excel的數(shù)據(jù)存到dataset后,我們要把dataset的數(shù)據(jù)存入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中的數(shù)據(jù),后續(xù)要存入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(); //數(shù)據(jù)庫登錄 //注意Integrated Security不寫(false)表示必須要用pwd登錄,true表示不用密碼也能進(jìn)入數(shù)據(jù)庫 public static string ConnStr = ConfigurationManager.AppSettings["ConnStr"].ToString(); //用于記錄log的時候,機(jī)臺名字 public static string machineName = "test"; #endregion #region 定時器的初始化,及其事務(wù) //這個按鈕用于模擬服務(wù)(定時器)啟動 public void InitTimer() { //DFL的定時器 TimModel.Interval = 15 * 1000; //定時器的事務(wù) TimModel.Elapsed += new ElapsedEventHandler(ElapsedEventDFL); TimModel.Enabled = true; TimModel.AutoReset = true; } private void ElapsedEventDFL(object source, ElapsedEventArgs e) { if (GetFiles("test")) { //多次讀取數(shù)據(jù),存在多個文件時但其中某個文件在使用的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初始化設(shè)置 Log4Application Log4App = new Log4Application(); /*用于移動源文件到指定文件夾,也就是備份源數(shù)據(jù)文件 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"; //讀取數(shù)據(jù)源文件的文件夾路徑(Working) string WorkingPath = WPath + equipName + " Equipment Temp. monitoring by third tool\\Working"; //初始化system.IO的配置(路徑) DirectoryInfo directoryInfo = new DirectoryInfo(WorkingPath); //用文件流來獲取文件夾中所有文件,存放到 FileInfo[] files = directoryInfo.GetFiles(); //循環(huán)的把所有機(jī)臺數(shù)據(jù)備份到Achieve文件夾 try { foreach (FileInfo file in files) // Directory.GetFiles(srcFolder) { //使用IO中的Moveto函數(shù)進(jìn)行移動文件操作 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 數(shù)據(jù)源, 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中的數(shù)據(jù)存入SQL server public void DataToSql(string equipName) { //初始化配置 sqlserver的服務(wù)器名用戶等 SqlConnection Conn = new SqlConnection(ConnStr); Conn.Open(); //配置SQLBulkCopy方法,真正用于復(fù)制數(shù)據(jù)到數(shù)據(jù)庫的方法 SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnStr, SqlBulkCopyOptions.UseInternalTransaction) { DestinationTableName = "ModelTest_HD" }; try { foreach (DataColumn item in ds.Tables[0].Columns) { //只復(fù)制所選的相關(guān)列 bulkCopy.ColumnMappings.Add(item.ColumnName, item.ColumnName); } //開始復(fù)制到sql,每次在數(shù)據(jù)庫中添加 bulkCopy.WriteToServer(ds.Tables[0]); bulkCopy.Close(); //copy完了,要清空ds的內(nèi)容,不然會引起循環(huán)寫入上一個內(nèi)容 ds.Tables.Clear(); } catch (Exception ex) { } finally { //關(guān)閉數(shù)據(jù)庫通道 Conn.Close(); } } protected override void OnStart(string[] args) { //啟動服務(wù)時做的事情 } protected override void OnStop() { //停止服務(wù)時做的事情 } } }
認(rèn)真看注釋可以看出本程序的邏輯就是:
1、讀取到Excel數(shù)據(jù)
2、存Excel數(shù)據(jù)到SQL server
3、備份Excel文件到另一個文件夾
其中一些功能大家可以看一看,注釋也寫的很清楚。對于初學(xué)者 configurationmanager的內(nèi)容是在 app.config中設(shè)置的,這里直接去配置就行(類似html)
foreach (DataColumn item in ds.Tables[0].Columns) { //只復(fù)制所選的相關(guān)列 bulkCopy.ColumnMappings.Add(item.ColumnName, item.ColumnName); }
注意這一段代碼,表示只復(fù)制數(shù)據(jù)庫與Excel表中 “列名”一致的數(shù)據(jù),如果不一致就不復(fù)制。(注意數(shù)據(jù)的格式,int還char 這些必須弄清楚)
然后bulkCopy.WriteToServer(ds.Tables[0])這里,就是把ds.tables的數(shù)據(jù)復(fù)制到SQLserver ,Tables[0]表示ds第一張表(其實我們也只有一張表,至于怎么在dataset中新建table自己可以查查資料)
最后的最后,注意釋放這些dataset,或者table。然后通道也記得close一下。
祝大家學(xué)習(xí)快樂。
以上就是C# 從Excel讀取數(shù)據(jù)向SQL server寫入的詳細(xì)內(nèi)容,更多關(guān)于c# 向SQL server寫入數(shù)據(jù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
jQuery uploadify在谷歌和火狐瀏覽器上傳失敗的解決方案
jquery.uploadify插件是一個基于jquery來實現(xiàn)上傳的,這個插件很好用,每一次向后臺發(fā)送數(shù)據(jù)流請求時,ie會自動把本地cookie存儲捆綁在一起發(fā)送給服務(wù)器。但firefox、chrome不會這樣做,他們會認(rèn)為這樣不安全,下面介紹下jQuery uploadify上傳失敗的解決方案2015-08-08C#使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間
這篇文章主要為大家詳細(xì)介紹了C#如何使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,有需要的小伙伴可以參考下2024-01-01深入DropDownList用法的一些學(xué)習(xí)總結(jié)分析
本篇文章是對DropDownList的用法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06Dictionary擴(kuò)展基礎(chǔ)類向字典中添加鍵和值
Dictionary<TKey, TValue> 類是常用的一個基礎(chǔ)類,但用起來有時確不是很方便。本文逐一討論,并使用擴(kuò)展方法解決2013-11-11C#實現(xiàn)微信公眾號群發(fā)消息(解決一天只能發(fā)一次的限制)實例分享
經(jīng)過幾天研究網(wǎng)上的代碼和謝燦大神的幫忙,今天終于用C#實現(xiàn)了微信公眾號群發(fā)消息,現(xiàn)在分享一下2013-09-09