C# 從Excel讀取數(shù)據向SQL server寫入
第一次寫C#與sql的東西,主要任務是從Excel讀取數(shù)據,再存到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ù)據源, 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的內容,select * 表示選取sheet中所有行和列;
strConn用于設置讀取的方法,provider的設置很重要,ACE表示最新的.xlsx文件,jet 表示讀取.xls文件,兩者有點區(qū)別,DataSource表示文件名,包括路徑。
OleDbDataAdapter 用于按(命令)去執(zhí)行填充dataset的功能
dataset簡而言之可以理解為 虛擬的 數(shù)據庫或是Excel文件。而dataset里的datatable 可以理解為數(shù)據庫中的table活著Excel里的sheet(Excel里面不是可以新建很多表嗎)。
這樣說應該很容易懂了,相當于dataset只是暫時存放下數(shù)據,微軟官方解釋是存在內存中。至于為啥要找個“中介”來存數(shù)據,這個估計是為了和SQL匹配。
好了,接下來說下這次的重點。
在把Excel的數(shù)據存到dataset后,我們要把dataset的數(shù)據存入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ù)據,后續(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ù)據庫登錄
//注意Integrated Security不寫(false)表示必須要用pwd登錄,true表示不用密碼也能進入數(shù)據庫
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"))
{
//多次讀取數(shù)據,存在多個文件時但其中某個文件在使用的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();
/*用于移動源文件到指定文件夾,也就是備份源數(shù)據文件
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ù)據源文件的文件夾路徑(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)的把所有機臺數(shù)據備份到Achieve文件夾
try
{
foreach (FileInfo file in files) // Directory.GetFiles(srcFolder)
{
//使用IO中的Moveto函數(shù)進行移動文件操作
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ù)據源, 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ù)據存入SQL server
public void DataToSql(string equipName)
{
//初始化配置 sqlserver的服務器名用戶等
SqlConnection Conn = new SqlConnection(ConnStr);
Conn.Open();
//配置SQLBulkCopy方法,真正用于復制數(shù)據到數(shù)據庫的方法
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,每次在數(shù)據庫中添加
bulkCopy.WriteToServer(ds.Tables[0]);
bulkCopy.Close();
//copy完了,要清空ds的內容,不然會引起循環(huán)寫入上一個內容
ds.Tables.Clear();
}
catch (Exception ex)
{
}
finally
{
//關閉數(shù)據庫通道
Conn.Close();
}
}
protected override void OnStart(string[] args)
{
//啟動服務時做的事情
}
protected override void OnStop()
{
//停止服務時做的事情
}
}
}
認真看注釋可以看出本程序的邏輯就是:
1、讀取到Excel數(shù)據
2、存Excel數(shù)據到SQL server
3、備份Excel文件到另一個文件夾
其中一些功能大家可以看一看,注釋也寫的很清楚。對于初學者 configurationmanager的內容是在 app.config中設置的,這里直接去配置就行(類似html)
foreach (DataColumn item in ds.Tables[0].Columns)
{
//只復制所選的相關列
bulkCopy.ColumnMappings.Add(item.ColumnName, item.ColumnName);
}
注意這一段代碼,表示只復制數(shù)據庫與Excel表中 “列名”一致的數(shù)據,如果不一致就不復制。(注意數(shù)據的格式,int還char 這些必須弄清楚)
然后bulkCopy.WriteToServer(ds.Tables[0])這里,就是把ds.tables的數(shù)據復制到SQLserver ,Tables[0]表示ds第一張表(其實我們也只有一張表,至于怎么在dataset中新建table自己可以查查資料)
最后的最后,注意釋放這些dataset,或者table。然后通道也記得close一下。
祝大家學習快樂。
以上就是C# 從Excel讀取數(shù)據向SQL server寫入的詳細內容,更多關于c# 向SQL server寫入數(shù)據的資料請關注腳本之家其它相關文章!
相關文章
jQuery uploadify在谷歌和火狐瀏覽器上傳失敗的解決方案
jquery.uploadify插件是一個基于jquery來實現(xiàn)上傳的,這個插件很好用,每一次向后臺發(fā)送數(shù)據流請求時,ie會自動把本地cookie存儲捆綁在一起發(fā)送給服務器。但firefox、chrome不會這樣做,他們會認為這樣不安全,下面介紹下jQuery uploadify上傳失敗的解決方案2015-08-08
C#使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間
這篇文章主要為大家詳細介紹了C#如何使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以參考下2024-01-01
C#實現(xiàn)微信公眾號群發(fā)消息(解決一天只能發(fā)一次的限制)實例分享
經過幾天研究網上的代碼和謝燦大神的幫忙,今天終于用C#實現(xiàn)了微信公眾號群發(fā)消息,現(xiàn)在分享一下2013-09-09

