首页 > 代码库 > Excel中 随机抽取n行 存储在access中
Excel中 随机抽取n行 存储在access中
string[] re = new string [50]; Random w = new Random(); /// <summary> /// 产生50个不同的数 以随机抽题 /// </summary> /// <returns></returns> private string[] Random() { int[] res = new int[50]; int c = 0; do { int temp = w.Next(1, 200); if (!isa(temp, res)) res[c++] = temp; } while (c < 50); for (int i=0;i <res.Length ;i++) { re[i] = res[i].ToString(); } return re; } private bool isa(int x, int[] arr) { for (int i = 0; i < arr.Length; i++) if (x == arr[i]) return true; return false; } string strGetDataFromExcel = ""; string strInsertIntoAccess = ""; OleDbConnection oleDbConnAccess; OleDbConnection oleDbConnExcel; OleDbCommand oleDbCmdAccess; OleDbCommand oleDbCmdExcel; OleDbDataReader oleDbDataReaderExcel; //test.accdb 为 目标文件 www.xlsx为源文件 private void ss() { string[] s = Random(); oleDbConnAccess = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath.Trim() + "\\test.accdb"); oleDbConnExcel = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Jet OLEDB:Database Password=;Extended properties=Excel 5.0;Data Source=" + Application.StartupPath.Trim() + "\\www.xlsx"); oleDbConnExcel.Open(); strGetDataFromExcel = "SELECT * FROM [Sheet1$]"; oleDbCmdExcel = new OleDbCommand(strGetDataFromExcel, oleDbConnExcel); oleDbDataReaderExcel = oleDbCmdExcel.ExecuteReader(); if (oleDbDataReaderExcel.HasRows == true) { oleDbConnAccess.Open(); for (; ; ) { if (oleDbDataReaderExcel.Read() == true) { for (int i = 0; i < 31; i++) { if (oleDbDataReaderExcel.GetValue(0).ToString().Equals(s[i])) { strInsertIntoAccess = "insert into w(Q,A,B,C,D) values(‘" + oleDbDataReaderExcel.GetValue(1).ToString() + "‘,‘" + oleDbDataReaderExcel.GetValue(2).ToString() + "‘,‘" + oleDbDataReaderExcel.GetValue(3).ToString() + "‘,‘" + oleDbDataReaderExcel.GetValue(4).ToString() + "‘,‘" + oleDbDataReaderExcel.GetValue(5).ToString() + "‘) "; oleDbCmdAccess = new OleDbCommand(strInsertIntoAccess, oleDbConnAccess); oleDbCmdAccess.ExecuteNonQuery(); oleDbCmdAccess.Dispose(); } } } else break; } oleDbConnAccess.Close(); } oleDbDataReaderExcel.Close(); oleDbCmdExcel.Dispose(); oleDbConnExcel.Close(); }
Excel中 随机抽取n行 存储在access中
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。