标签:des style blog http io ar color os 使用
对于C#Execl数据的导入导出大家不感到陌生,这是一个项目中经常回遇到的功能,今天在这里讲的事,使用SqlBulkCopy类实现导入Excel大批量的数据导入。
/// <summary> /// 数据库对应表 /// </summary> /// <returns></returns> private static DataTable GetDeliveryOrderTable() { DataTable dt = new DataTable(); dt.Columns.Add("ShipperID", typeof(string)); dt.Columns.Add("ConsigneeProvince", typeof(string)); dt.Columns.Add("ConsigneeName", typeof(string)); dt.Columns.Add("ConsigneeContact", typeof(string)); dt.Columns.Add("ConsigneeAddress", typeof(string)); dt.Columns.Add("ConsigneeMobile", typeof(string)); dt.Columns.Add("ShipperName", typeof(string)); dt.Columns.Add("TransportDate", typeof(DateTime)); dt.Columns.Add("PlanEndDate", typeof(DateTime)); dt.Columns.Add("EndDate", typeof(DateTime)); dt.Columns.Add("Status", typeof(string)); dt.Columns.Add("CheckStatus", typeof(string)); dt.Columns.Add("OrderSource", typeof(string)); dt.Columns.Add("Creator", typeof(string)); dt.Columns.Add("Creator_ID", typeof(string)); dt.Columns.Add("CreateTime", typeof(DateTime)); return dt; }
/// <summary> /// 保存数据 /// </summary> bool ExcelData_OnDataSave(DataRow dr) { bool IsRead = false; DeliveryOrderInfo doi_info = new DeliveryOrderInfo();//运单表 //实例化一个和数据库一样的DataTable DataTable dt_DeliveryOrder = GetDeliveryOrderTable(); DataRow dr_DeliveryOrder = dt_DeliveryOrder.NewRow(); dr_DeliveryOrder["ShipperID"] = dr["发运单号"].ToString(); dr_DeliveryOrder["ConsigneeProvince"] = dr["省份"].ToString(); dr_DeliveryOrder["ConsigneeContact"] = dr["收货人"].ToString(); dr_DeliveryOrder["ConsigneeAddress"] = dr["地址"].ToString(); dr_DeliveryOrder["ConsigneeMobile"] = dr["联系电话"].ToString(); dr_DeliveryOrder["ShipperName"] = dr["货运部"].ToString(); dr_DeliveryOrder["TransportDate"] = Convert.ToDateTime(dr["发运日期"]); dr_DeliveryOrder["PlanEndDate"] = Convert.ToDateTime(dr["预计到货日期"]); dr_DeliveryOrder["EndDate"] = Convert.ToDateTime(dr["实际到货日期"]); dr_DeliveryOrder["Status"] = "在途中"; dr_DeliveryOrder["CheckStatus"] = "未审核"; dr_DeliveryOrder["OrderSource"] = "批量导入"; dt_DeliveryOrder.Rows.Add(dr_DeliveryOrder);//运单表 if (deliveryOrderInfo == null)//判断是否有重复发运单号 { #region MyRegion if (dt_DeliveryOrder != null && dt_DeliveryOrder.Rows.Count > 0) { using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { #region try try { using (SqlBulkCopy bulk = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, trans)) { //设置每一批次中的行数。在每一批次结束时,将该批次中的行发送到服务器。 bulk.BatchSize = 1000; //设置服务器上目标表的名称 bulk.DestinationTableName = "TMS_DeliveryOrder"; //已重载。将所有行从数据源复制到SqlBulkCopy对象的DestinationTableName属性指定的目标表中。 bulk.WriteToServer(dt_DeliveryOrder); IsRead = true; trans.Commit(); } } catch (Exception ex) { Console.Write(ex.Message); IsRead = false; trans.Rollback(); } finally { conn.Close(); } #endregion } } } #endregion } return success; }
标签:des style blog http io ar color os 使用
原文地址:http://www.cnblogs.com/wuxiaohui/p/4116510.html