Excel 2010数据导入:
实现的思路很简单,读取Excel的数据,可以使用OLEdbconnection ,然后将读取到的数据存入DataSet,最后将DataSet中的数据提交给数据库。这样的话就需要你的Excel数据源文件的变化很少,甚至不变,这样的好处是开发时间短,但是扩展性差,源文件有一点变动就需要修改程序。
也可以用Excel.Application,这样就可以灵活的读取Excel源文件的数据,由于时间赶,没有用这种方法。
读取数据,存入DataSet:
View Code
1 #region 连接Excel,读取数据,并返回dataset 2 3 /// <summary> 4 /// 连接Excel 读取Excel数据 并返回DataSet数据集合 5 /// </summary> 6 /// <param name="filepath">Excel服务器路径</param> 7 /// <param name="tablename">Excel表名</param> 8 /// <returns></returns> 9 public static System.Data.DataSet GetExcelDataSet(string filepath) 10 { 11 string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'"; 12 13 OleDbConnection Conn = new OleDbConnection(strConn); 14 15 //create ArrayList object and save all the sheet Name list 16 ArrayList sheetNameList = new ArrayList(); 17 18 //获取配置Excel中sheet总数(这里是根据项目需求配置的) 如果需要导入Excel表格所有sheet数据则将此代码删除 19 //int sheetCount = Convert.ToInt32(ConfigurationManager.AppSettings["sheetCount"].ToString()); 20 21 DataSet dsExcel = new DataSet(); 22 try 23 { 24 if (Conn.State == ConnectionState.Closed) 25 { 26 Conn.Open(); 27 } 28 29 DataTable dtExcelSchema = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "Table" }); 30 string sheetName = string.Empty; 31 32 for (int j = 0; j < dtExcelSchema.Rows.Count; j++) 33 { 34 sheetName = string.Format("Sheet{0}$", j + 1); 35 sheetNameList.Add(sheetName); 36 } 37 } 38 catch (Exception ex) 39 { 40 throw new Exception(ex.Message.ToString(), ex); 41 } 42 43 //add all sheet into datatable 44 try 45 { 46 string strSql = string.Empty; 47 for (int i = 0; i < sheetNameList.Count; i++) 48 { 49 strSql = "select * from [" + sheetNameList[i].ToString() + "]"; 50 OleDbDataAdapter oda = new OleDbDataAdapter(strSql, Conn); 51 DataTable dtExcel = new DataTable(sheetNameList[i].ToString()); 52 oda.Fill(dtExcel); 53 54 if (dtExcel.Rows.Count > 0) 55 { 56 dsExcel.Tables.Add(dtExcel); 57 } 58 } 59 return dsExcel; 60 } 61 catch (Exception ex) 62 { 63 throw new Exception(ex.Message.ToString(), ex); 64 } 65 } 66 67 #endregion 连接Excel,读取数据,并返回dataset
插入数据库:
1 #region 将DataSet中读取到的数据插入数据库 2 3 /// <summary> 4 /// 将DataSet中读取到的数据插入数据库 5 /// </summary> 6 /// <param name="ds">DataSet数据集</param> 7 public void InsertExcelData(System.Data.DataSet ds) 8 { 9 //string strTime = "SELECT SYSDATE FROM DUAL"; 10 //string time = GetDBTime(strTime); 11 12 string user = Page.Request.UserHostName.ToString(); 13 14 if (ds.Tables[0].Rows.Count > 0) 15 { 16 for (int j = 0; j < ds.Tables.Count; j++) 17 { 18 for (int i = 0; i < ds.Tables[j].Rows.Count; i++) 19 { 20 DataRow dr = ds.Tables[j].Rows[i]; 21 22 //坏品ID 23 string bagid = dr["BAG_ID"].ToString().Trim(); 24 // 工厂代码、D2/D1/CA 25 string cellid = dr["CELL_ID"].ToString().Trim(); 26 //清洗类型 27 string tank = dr["TANK"].ToString().Trim(); 28 //清洗拉号 29 string lineno = dr["LINE_NO"].ToString().Trim(); 30 //清洗机号 31 string machine = dr["MACHINE"].ToString().Trim(); 32 //操作员工 33 string operators = dr["OPERATOR"].ToString().Trim(); 34 //工序号 35 string processid = dr["PROCESS_ID"].ToString().Trim(); 36 //状态 37 string status = dr["STATUS"].ToString().Trim(); 38 //环境 39 string location = dr["EVALUATION"].ToString().Trim(); 40 //测试时间 41 string testtime = dr["TEST_TIME"].ToString().Trim(); 42 //项目代码 43 string projectcode = dr["PROJ_CODE"].ToString().Trim(); 44 //头上/下 45 string updn = dr["UPDN"].ToString().Trim(); 46 47 string strSql = "insert into clean_brush_prod (BAG_ID,CELL_ID,Tank,Line_No,Machine,Operator,Process_Id,Status,Evaluation,Test_Time," 48 + " Create_User,Create_Time,Modify_User,Modify_Time,Proj_Code,Updn) values('" + bagid + "','" + cellid + "','" + tank + "','" + lineno + "'," 49 + " '" + machine + "','" + operators + "','" + processid + "','" + status + "','" + location + "',TO_DATE('" + testtime + "','MM/dd/YYYY HH24:MI:SS')," 50 + " '" + user + "',sysdate,'" + user + "',sysdate,'" + projectcode + "','" + updn + "')"; 51 52 if (cellid == "" || tank == "" || machine == "" || operators == "" || processid == "" || status == "" || testtime == "" || projectcode == "" || updn == "") 53 { 54 QXNET.Common.Utility.MsgBox("Information not null"); 55 break; 56 } 57 58 // 59 try 60 { 61 int n = Cls_DB_factory.ExcuteNonQuery(strSql); 62 63 if (n > 0) 64 { 65 QXNET.Common.Utility.MsgBox("Sucess, insert " + ds.Tables[j].Rows.Count + " row data"); 66 //msglbl.Text = "Sucess Inserted " + ds.Tables[j].Rows.Count.ToString() + "Row Data"; 67 } 68 else 69 { 70 QXNET.Common.Utility.MsgBox("Insert Data Faild"); 71 } 72 } 73 catch (Exception ex) 74 { 75 throw new Exception(ex.Message.ToString(), ex); 76 } 77 } 78 } 79 } 80 else 81 { 82 QXNET.Common.Utility.MsgBox("This Excel File No Data"); 83 } 84 } 85 86 #endregion 将DataSet中读取到的数据插入数据库
这样的话基本就搞定了Excel数据插入Oracle数据库(Mysql或其他的数据库只是DB connection 不同罢了)。
Excel 2010数据导出:
实现的思路是直接的respone.write()写出去,或者呢是用GridView导出,但两者是大同小异,当然你也可以导出到TXT文本文档或CSV,代码见分晓。
Response.Charset = "UTF-8"; Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
//filenames=filename.csv /filename.txt Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); Response.ContentType = "application/ms-excel";
//Response.contentType="Other document type" EnableViewState = false; System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); string StrSQL = ""; StrSQL = this.getStrSQL(); DataSet DS = new DataSet(); DS = Cls_DB_factory._DataSet(StrSQL); gview.DataSource = DS.Tables[0]; gview.DataBind(); gview.RenderControl(oHtmlTextWriter); // this.GridView1.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End();
与大家分享,
若有误,请指正!