C#_根据Excel表创建Access数据库以及显示Access数据库表的信息到DataGridView上
- 基于Excel中的表创建Access数据库:
string DBPath = ""; OleDbConnection conn; public static int ColumnNumber(string colAdress) { int[] digits = new int[colAdress.Length]; for (int i = 0; i < colAdress.Length; ++i) { digits[i] = Convert.ToInt32(colAdress[i]) - 64; } int mul = 1; int res = 0; for (int pos = digits.Length - 1; pos >= 0; --pos) { res += digits[pos] * mul; mul *= 26; } return res; } private string GetAllNamesForCreate(string[] strArr) { string result = ""; Microsoft.Office.Interop.Excel.Application app = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"your excel path", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "", false, false, 0, true, false, false); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; for (int i=0;i<strArr.Length;i++) { int col = ColumnNumber(strArr[i]); string colName = Convert.ToString(xlWorksheet.Cells[1, col].Value); result += " [" + colName + "]" + " Text,"; } xlWorkbook.Close(0); xlApp.Quit(); return result.Remove(result.Length-1,1); } private string GetAllNamesForSelect(string[] strArr) { string result = ""; Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"excel path", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "", false, false, 0, true, false, false); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; for (int i = 0; i < strArr.Length; i++) { int col = ColumnNumber(strArr[i]); string colName = Convert.ToString(xlWorksheet.Cells[1, col].Value); result += " [" + colName + "],"; } xlWorkbook.Close(0); xlApp.Quit(); return result.Remove(result.Length - 1, 1); } private void button1_Click(object sender, EventArgs e) { string[] arr = { "C", "D" }; DBPath = @"your Access database path"; if (!File.Exists(DBPath)) { ADOX.Catalog cat = new ADOX.Catalog(); cat.Create(Convert.ToString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") + DBPath); cat = null; } conn = new OleDbConnection(Convert.ToString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") + DBPath); conn.Open(); try { using (OleDbCommand cmd = new OleDbCommand($"CREATE TABLE [TEST] ([id] COUNTER PRIMARY KEY, {GetAllNamesForCreate(arr)} );", conn)) { cmd.ExecuteNonQuery(); } } catch (Exception ex) { if (ex != null) ex = null; } string path; path = @"excel path"; string _conn = "provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";Extended Properties=\'Excel 8.0;HDR=Yes;IMEX=1;\';"; try { using (OleDbConnection conn = new OleDbConnection(_conn)) { using (OleDbCommand cmd = new OleDbCommand()) { cmd.Connection = conn; cmd.CommandText = "INSERT INTO [MS Access;Database=" + DBPath + $"].[test] SELECT {GetAllNamesForSelect(arr)} FROM [Sheet1$]"; conn.Open(); cmd.ExecuteNonQuery(); } } MessageBox.Show("The import is complete!"); } catch (Exception e1) { MessageBox.Show("Import Failed, correct Column name in the sheet!" + Environment.NewLine + "Error Message:" + Environment.NewLine + e1.Message); } }
- 打开一张Excel表,将所有表名显示在combobox中,并根据所选的值将结果显示在datagridview中:
public string OpenFile() { OpenFileDialog OFD = new OpenFileDialog() { AddExtension = true, CheckFileExists = true, Filter = "Excel files Excel files (*.xls)|*.xls", Multiselect = false, Title = "Select an workbook to open" }; if (OFD.ShowDialog() == DialogResult.OK) return OFD.FileName; else return null; } string path; private void button1_Click(object sender, EventArgs e) { path = OpenFile(); Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook excelBook = xlApp.Workbooks.Open(path); String[] excelSheets = new String[excelBook.Worksheets.Count]; int i = 0; foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in excelBook.Worksheets) { excelSheets[i] = wSheet.Name; i++; } comboBox1.Items.Clear(); comboBox1.Items.AddRange(excelSheets); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { var ds = new DataSet(); string con = "provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";Extended Properties=\'Excel 8.0;HDR=NO;IMEX=1;\';"; using (OleDbConnection connection = new OleDbConnection(con)) { connection.Open(); OleDbCommand cmd = new OleDbCommand(); OleDbDataAdapter oleda = new OleDbDataAdapter(); DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string sheetName = string.Empty; if (dt != null) { dt = (from dataRow in dt.AsEnumerable() where !dataRow["TABLE_NAME"].ToString().Contains("FilterDatabase") select dataRow).CopyToDataTable(); sheetName = dt.Rows[comboBox1.SelectedIndex]["TABLE_NAME"].ToString(); } cmd.Connection = connection; cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM [" + sheetName + "]"; oleda = new OleDbDataAdapter(cmd); oleda.Fill(ds, "excelData"); } dataGridView1.DataSource = ds.Tables["excelData"]; }
版权声明:本文为xingyz原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。