C#數據庫數據導入導出系列之四 WinForm數據庫導入導出到Excel
在日常的項目中,Excel,Word,txt等格式的數據導入到數據庫中是很常見的,我在這里做一下總結
這里將分為Asp.net導入Sql Server,Oracle數據庫和WinForm導入Sql Server,Oracle數據庫。
這里將的數據庫數據庫導入導出,其實對Sql Server 和Oracle都是通用的
如果使用ADO.Net連接Oracle數據庫,需要在引用里添加“System.Data.OracleClient ”,其他方面與連接Sql Server數據庫是一樣的
SqlConnection cn = new SqlConnection();
OracleConnection oraleCn = new OracleConnection();
如果使用諸如Ibatis等持久層框架的話,唯一的區別就是在數據庫連接語句上的差別而已。下面是兩個例子
Oracle:Data Source=192.168.0.11/Contact;User ID=system;Password=ss;Unicode=True
Sql Server: Data Source=Contact;Server=localhost;uid=sa;pwd=ss
1,數據庫導出到Excel
先看界面
然后是代碼

1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.Diagnostics; 10 using Microsoft.Office.Interop.Excel; 11 using System.Reflection; 12 using System.IO; 13 using System.Data.SqlClient; 14 using System.Data.OracleClient; 15 16 namespace SqlServer__Excel 17 { 18 public partial class SqlDB_To_Excel : Form 19 { 20 public SqlDB_To_Excel() 21 { 22 InitializeComponent(); 23 } 24 25 private Microsoft.Office.Interop.Excel.Application myExcel = null; 26 27 private void button1_Click(object sender, EventArgs e) 28 { 29 print(dataGridView1); 30 } 31 32 public void print(DataGridView dataGridView1) 33 { 34 //導出到execl 35 try 36 { 37 SaveFileDialog saveFileDialog = new SaveFileDialog(); 38 saveFileDialog.Filter = "導出Excel (*.xls)|*.xls"; 39 saveFileDialog.FilterIndex = 0; 40 saveFileDialog.RestoreDirectory = true; 41 saveFileDialog.CreatePrompt = true; 42 saveFileDialog.Title = "導出文件保存路徑"; 43 saveFileDialog.ShowDialog(); 44 string strName = saveFileDialog.FileName; 45 if(strName.Length != 0) 46 { 47 //沒有數據的話就不往下執行 48 if(dataGridView1.Rows.Count == 0) 49 return; 50 51 // toolStripProgressBar1.Visible = true; 52 System.Reflection.Missing miss = System.Reflection.Missing.Value; 53 //實例化一個Excel.Application對象 54 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 55 excel.Application.Workbooks.Add(true); 56 excel.Visible = false;//若是true,則在導出的時候會顯示EXcel界面。 57 if(excel == null) 58 { 59 MessageBox.Show("EXCEL無法啟動!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); 60 return; 61 } 62 Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks; 63 Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss)); 64 Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet; 65 sheet.Name = "test"; 66 int m = 0, n = 0; 67 //生成Excel中列頭名稱 68 for(int i = 0; i < dataGridView1.Columns.Count; i++) 69 { 70 excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;//輸出DataGridView列頭名 71 } 72 //把DataGridView當前頁的數據保存在Excel中 73 for(int i = 0; i < dataGridView1.Rows.Count - 1; i++) 74 { 75 for(int j = 0; j < dataGridView1.Columns.Count; j++) 76 { 77 if(dataGridView1[j, i].ValueType == typeof(string)) 78 { 79 excel.Cells[i + 2, j + 1] = "'" + dataGridView1[j, i].Value.ToString(); 80 } 81 else 82 { 83 excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString(); 84 } 85 } 86 } 87 sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss); 88 book.Close(false, miss, miss); 89 books.Close(); 90 excel.Quit(); 91 System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); 92 System.Runtime.InteropServices.Marshal.ReleaseComObject(book); 93 System.Runtime.InteropServices.Marshal.ReleaseComObject(books); 94 System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 95 GC.Collect(); 96 MessageBox.Show("數據已經成功導出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 97 // toolStripProgressBar1.Value = 0; 98 System.Diagnostics.Process.Start(strName); 99 } 100 } 101 catch(Exception ex) 102 { 103 MessageBox.Show(ex.Message, "錯誤提示"); 104 } 105 } 106 107 public void printAll(System.Data.DataTable dt) 108 { 109 //導出到execl 110 try 111 { 112 SaveFileDialog saveFileDialog = new SaveFileDialog(); 113 saveFileDialog.Filter = "導出Excel (*.xls)|*.xls"; 114 saveFileDialog.FilterIndex = 0; 115 saveFileDialog.RestoreDirectory = true; 116 saveFileDialog.CreatePrompt = true; 117 saveFileDialog.Title = "導出文件保存路徑"; 118 saveFileDialog.ShowDialog(); 119 string strName = saveFileDialog.FileName; 120 if(strName.Length != 0) 121 { 122 //沒有數據的話就不往下執行 123 if(dt.Rows.Count == 0) 124 return; 125 126 // toolStripProgressBar1.Visible = true; 127 System.Reflection.Missing miss = System.Reflection.Missing.Value; 128 //實例化一個Excel.Application對象 129 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 130 excel.Application.Workbooks.Add(true); 131 excel.Visible = false;//若是true,則在導出的時候會顯示EXcel界面。 132 if(excel == null) 133 { 134 MessageBox.Show("EXCEL無法啟動!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); 135 return; 136 } 137 Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks; 138 Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss)); 139 Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet; 140 sheet.Name = "test"; 141 int m = 0, n = 0; 142 143 144 //生成Excel中列頭名稱 145 for(int i = 0; i < dt.Columns.Count; i++) 146 { 147 excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;//輸出DataGridView列頭名 148 } 149 150 //把DataGridView當前頁的數據保存在Excel中 151 if(dt.Rows.Count > 0) 152 { 153 for(int i = 0; i < dt.Rows.Count; i++)//控制Excel中行,上下的距離,就是可以到Excel最下的行數,比數據長了報錯,比數據短了會顯示不完 154 { 155 for(int j = 0; j < dt.Columns.Count; j++)//控制Excel中列,左右的距離,就是可以到Excel最右的列數,比數據長了報錯,比數據短了會顯示不完 156 { 157 string str = dt.Rows[i][j].ToString(); 158 excel.Cells[i + 2, j + 1] = "'" + str;//i控制行,從Excel中第2行開始輸出第一行數據,j控制列,從Excel中第1列輸出第1列數據,"'" +是以string形式保存,所以遇到數字不會轉成16進制 159 } 160 } 161 } 162 sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss); 163 book.Close(false, miss, miss); 164 books.Close(); 165 excel.Quit(); 166 System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); 167 System.Runtime.InteropServices.Marshal.ReleaseComObject(book); 168 System.Runtime.InteropServices.Marshal.ReleaseComObject(books); 169 System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 170 171 GC.Collect(); 172 MessageBox.Show("數據已經成功導出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 173 // toolStripProgressBar1.Value = 0; 174 System.Diagnostics.Process.Start(strName); 175 } 176 } 177 catch(Exception ex) 178 { 179 MessageBox.Show(ex.Message, "錯誤提示"); 180 } 181 } 182 183 private void SqlDB_To_Excel_Load(object sender, EventArgs e) 184 { 185 dataGridView1.DataSource = GetDataTableFromSqlServer(); 186 } 187 188 private void button2_Click(object sender, EventArgs e) 189 { 190 printAll(GetDataTableFromSqlServer()); 191 } 192 193 private System.Data.DataTable GetDataTableFromSqlServer() 194 { 195 string sqlconn = "database=database1;server=localhost;uid=sa;pwd=sa"; 196 SqlConnection cn = new SqlConnection(sqlconn); 197 string cmdText = "select * from users"; 198 SqlDataAdapter da = new SqlDataAdapter(cmdText, cn); 199 DataSet ds = new DataSet(); 200 da.Fill(ds, "table1"); 201 return ds.Tables[0]; 202 } 203 204 private System.Data.DataTable GetDataTableFromOracle() 205 { 206 string oracleconn = "Data Source=192.168.2.105/Database1;User ID=system;Password=ss;Unicode=True"; 207 OracleConnection cn = new OracleConnection(oracleconn); 208 string cmdText = "select * from users"; 209 OracleDataAdapter da = new OracleDataAdapter(cmdText, cn); 210 DataSet ds = new DataSet(); 211 da.Fill(ds, "table1"); 212 return ds.Tables[0]; 213 } 214 } 215 }
結果:
代碼的思想就是將數據從數據庫中讀出到DataTable或者DataGridView中,然后遍歷他們的每一個單元格的值,給Excel對應的單元格賦值。
使用DataTable作為遍歷的對象,是為了去除分頁的困擾。
看到這里,如果換一個List<T>對象集合,也應該能導出到數據庫中了。
2,Excel數據導入到數據庫
在WinForm中Excel導入到數據庫中和在WebForm中的導入過程是一樣的。可參見前面的內容。