接上文: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:ATSscottzhangDesktopATS工作临时文件 emp eststudent.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; } }