使用C#將Excel檔案中資料匯入SQL Server資料庫
阿新 • • 發佈:2019-01-27
由於專案中加入了新的功能,可以使管理員向資料庫中匯入Excel資料。因此,在商品管理這塊需要對Excel進行操作,在網上查了些資料,根據專案的實際情況進行了一定的優化,這裡簡單的介紹下。
C#程式碼
/// <summary>
/// 上傳Excel檔案,並將資料匯入到資料庫
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void lbtnSure_Click(object sender, EventArgs e)
{
// 定義變數,並賦初值
string url = this.fileUpLoad.PostedFile.FileName;
string urlLocation = "";
// 判斷傳輸地址是否為空
if (url == "")
{
// 提示“請選擇Excel檔案”
Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script defer>alert('請選擇97~2003版Excel檔案!');</script>");
return;
}
// 判斷獲取的是否為地址,而非檔名
if (url.IndexOf("\\") > -1)
{
// 獲取檔名
urlLocation = url.Substring(url.LastIndexOf("\\") + 1);//獲取檔名
}
else
{
// url為檔名時,直接獲取檔名
urlLocation = url;
}
// 判斷指定目錄下是否存在資料夾,如果不存在,則建立
if (!Directory.Exists(Server.MapPath("~\\up")))
{
// 建立up資料夾
Directory.CreateDirectory(Server.MapPath("~\\up"));
}
//在系統中建資料夾up,並將excel檔案另存
this.fileUpLoad.SaveAs(Server.MapPath("~\\up") + "\\" + urlLocation);//記錄檔名到伺服器相對應的資料夾中
// Response.Write(urlLocation);
// 取得儲存到伺服器端的檔案路徑
string strpath = Server.MapPath("~\\up") + "\\" + urlLocation;
// 取得config中的欄位
string connectionString = ConfigurationManager.AppSettings["Connect"].ToString();
string strCon = ConfigurationManager.AppSettings["strUpLoad"].ToString();
// 替換變數
strCon = strCon.Replace("$Con$", strpath);
// 初始化匯入Excel物件
ImportExcel excel = new ImportExcel();
// 呼叫方法,將Excel檔案匯入資料庫
excel.TransferData(strCon, "t_Goods", connectionString);
}
TransferData類
public void TransferData(string strCon, string sheetName, string connectionString)
{
DataSet ds = new DataSet();
try
{
//獲取全部資料
OleDbConnection conn = new OleDbConnection(strCon);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
strExcel = string.Format("select * from [{0}$]", sheetName);
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(ds, sheetName);
//如果目標表不存在則建立,excel檔案的第一行為列標題,從第二行開始全部都是資料記錄
string strSql = string.Format("if not exists(select * from sysobjects where name = '{0}') create table {0}(", sheetName); //以sheetName為表名
foreach (System.Data.DataColumn c in ds.Tables[0].Columns)
{
strSql += string.Format("[{0}] varchar(255),", c.ColumnName);
}
strSql = strSql.Trim(',') + ")";
using (System.Data.SqlClient.SqlConnection sqlconn = new System.Data.SqlClient.SqlConnection(connectionString))
{
sqlconn.Open();
System.Data.SqlClient.SqlCommand command = sqlconn.CreateCommand();
command.CommandText = strSql;
command.ExecuteNonQuery();
sqlconn.Close();
}
//用bcp匯入資料
//excel檔案中列的順序必須和資料表的列順序一致,因為資料匯入時,是從excel檔案的第二行資料開始,不管資料表的結構是什麼樣的,反正就是第一列的資料會插入到資料表的第一列欄位中,第二列的資料插入到資料表的第二列欄位中,以此類推,它本身不會去判斷要插入的資料是對應資料表中哪一個欄位的
using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))
{
bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
bcp.BatchSize = 100;//每次傳輸的行數
bcp.NotifyAfter = 100;//進度提示的行數
bcp.DestinationTableName = sheetName;//目標表
bcp.WriteToServer(ds.Tables[0]);
}
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
//進度顯示
void bcp_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)
{
}
}
Web介面樣式