1. 程式人生 > >C# 平面文件批量導數據到DB(三)

C# 平面文件批量導數據到DB(三)

ret tostring con roc shc 自己 static lln event

接上文:C# 平面文件批量導數據到DB(二),下面介紹第三種導文件的方法,這種方法需要DB裏面建一個用戶自定義表類型去接收客戶端傳進來的 DataTable。

1、創建一個Type在DB裏面

CREATE TYPE [dbo].[jk_test] AS TABLE(
    [c1] [varchar](60) NULL,
    [c2] [varchar](64) NULL,
    [c4] [varchar](50) NULL
)

2、創建一個SP在DB裏面,給前臺調用(表:_student 也要自己創建的,這裏不寫了)

ALTER PROCEDURE [dbo
].[sp_insert_jk_users] @usersTable jk_test READONLY AS INSERT INTO _student SELECT * FROM @usersTable

3、客戶端代碼:

        private void button1_Click(object sender, EventArgs e)
        {
            var sw = Stopwatch.StartNew();

            string strsql = "server = CSHC7256; uid = sa; pwd = Atser123; database = db_test
"; SqlConnection conn = new SqlConnection(strsql);//SQL數據庫連接對象,以數據庫鏈接字符串為參數 conn.Open(); //// Invokes the stored procedure. using (var cmd = new SqlCommand("sp_insert_jk_users", conn)) { //////////// string
excelFilePath = @"D:\ATS\scottzhang\Desktop\ATS工作\臨時文件\temp\test\student.xls"; //string excelSheetName = @"student";//這個是excel的sheet的名字 DataTable tb = new DataTable(); tb = GetExcelTableByOleDB(excelFilePath); ///////////// cmd.CommandType = CommandType.StoredProcedure; //// Adding a "structured" parameter allows you to insert tons of data with low overhead var param = new SqlParameter("@usersTable", SqlDbType.Structured) { Value = tb }; param.ParameterName = "@usersTable"; cmd.Parameters.Add(param); cmd.ExecuteNonQuery(); } sw.Stop(); } /// <summary> /// 讀取Excel[.xls](返回DataTable) /// </summary> /// <param name="path">Excel路徑</param> /// <returns></returns> public static DataTable GetExcelTableByOleDB(string path) { try { DataTable dt = new DataTable(); using (FileStream fs = new FileStream(path, FileMode.Open)) { IWorkbook workbook = new HSSFWorkbook(fs); ISheet sheet = workbook.GetSheetAt(0); int rfirst = sheet.FirstRowNum; int rlast = sheet.LastRowNum; IRow row = sheet.GetRow(rfirst); int cfirst = row.FirstCellNum; int clast = row.LastCellNum; for (int i = cfirst; i < clast; i++) { if (row.GetCell(i) != null) dt.Columns.Add(row.GetCell(i).StringCellValue, System.Type.GetType("System.String")); } row = null; for (int i = rfirst + 1; i <= rlast; i++) { DataRow r = dt.NewRow(); IRow ir = sheet.GetRow(i); for (int j = cfirst; j < clast; j++) { if (ir.GetCell(j) != null) { r[j] = ir.GetCell(j).ToString(); } } dt.Rows.Add(r); ir = null; r = null; } sheet = null; workbook = null; } return dt; } catch { System.Windows.Forms.MessageBox.Show("Excel格式錯誤或者Excel正由另一進程在訪問"); return null; } }

C# 平面文件批量導數據到DB(三)