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(); }
原文地址:http://8743025.blog.51cto.com/8733025/1567737