DataGridView導出數據到Excel中,可以導出當前頁和全部數據:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> 1 #region SaveDataGireViewtoExcel
2 public bool SaveDataGireViewtoExcel()
3 {
4 try
5 {
6 //實例化一個Excel.Application對象
7 Excel.Application excel =
8 new Excel.Application();
9
10 //讓後臺執行設置爲不可見,爲true的話會看到打開一個Excel,然後數據在往裏寫
11 excel.Visible = false;
12
13 //新增加一個工作簿,Workbook是直接保存,不會彈出保存對話框,加上Application會彈出保存對話框,值爲false會報錯
14 excel.Application.Workbooks.Add(true);
15 //生成Excel中列頭名稱
16 for (int i = 0; i < dataGridView_files.Columns.Count; i++)
17 {
18 excel.Cells[1, i + 1] = dataGridView_files.Columns[i].HeaderText;
19 }
20 //把DataGridView當前頁的數據保存在Excel中
21 for (int i = 0; i < dataGridView_files.Rows.Count - 1; i++)
22 {
23 for (int j = 0; j < dataGridView_files.Columns.Count; j++)
24 {
25 if (dataGridView_files[j, i].ValueType == typeof(string))
26 {
27 excel.Cells[i + 2, j + 1] = "'" + dataGridView_files[j, i].Value.ToString();
28 }
29 else
30 {
31 excel.Cells[i + 2, j + 1] = dataGridView_files[j, i].Value.ToString();
32 }
33 }
34 }
35
36 //設置禁止彈出保存和覆蓋的詢問提示框
37 excel.DisplayAlerts = false;
38 excel.AlertBeforeOverwriting = false;
39
40 //保存工作簿
41 excel.Application.Workbooks.Add(true).Save();
42 //保存excel文件
43 excel.Save(@System.Windows.Forms.Application.StartupPath+"\\aaa.xls");
44
45 //確保Excel進程關閉
46 excel.Quit();
47 excel = null;
48 GC.Collect();
49
50 return true;
51 }
52 catch (Exception ex)
53 {
54 MessageBox.Show(ex.Message, "錯誤提示");
55 }
56
57 return false;
58 }
59 #endregion
從Excel導入到DataGridView:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> 1 #region button_import_Click
2 private void button_import_Click(object sender, EventArgs e)
3 {
4 //打開一個文件選擇框
5 OpenFileDialog ofd = new OpenFileDialog();
6 ofd.Title = "Excel文件";
7 ofd.FileName = "";
8 ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//爲了獲取特定的系統文件夾,可以使用System.Environment類的靜態方法GetFolderPath()。該方法接受一個Environment.SpecialFolder枚舉,其中可以定義要返回路徑的哪個系統目錄
9 ofd.Filter = "Excel文件(*.xls)|*.xls";
10 ofd.ValidateNames = true; //文件有效性驗證ValidateNames,驗證用戶輸入是否是一個有效的Windows文件名
11 ofd.CheckFileExists = true; //驗證路徑有效性
12 ofd.CheckPathExists = true; //驗證文件有效性
13
14
15 string strName = string.Empty;
16 if (ofd.ShowDialog() == DialogResult.OK)
17 {
18 strName = ofd.FileName;
19 }
20
21 if (strName == "")
22 {
23 MessageBox.Show("沒有選擇Excel文件!無法進行數據導入");
24 return;
25 }
26 //調用導入數據方法
27 EcxelToDataGridView(strName, this.dataGridView_files);
28
29 }
30 #endregion
31
32 #region ExcelToDataGridView
33 public void EcxelToDataGridView(string filePath, DataGridView dgv)
34 {
35 //根據路徑打開一個Excel文件並將數據填充到DataSet中
36 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = "
37 + filePath + ";Extended Properties ='Excel 8.0;HDR=YES;IMEX=1'";//導入時包含Excel中的第一行數據,並且將數字和字符混合的單元格視爲文本進行導入
38 OleDbConnection conn = new OleDbConnection(strConn);
39 conn.Open();
40 string strExcel = "";
41 OleDbDataAdapter myCommand = null;
42 DataSet ds = null;
43 strExcel = "select * from [sheet1$]";
44 myCommand = new OleDbDataAdapter(strExcel, strConn);
45 ds = new DataSet();
46 myCommand.Fill(ds, "table1");
47
48 //根據DataGridView的列構造一個新的DataTable
49 DataTable tb = new DataTable();
50 foreach (DataGridViewColumn dgvc in dgv.Columns)
51 {
52 if (dgvc.Visible && dgvc.CellType != typeof(DataGridViewCheckBoxCell))
53 {
54 DataColumn dc = new DataColumn();
55 dc.ColumnName = dgvc.DataPropertyName;
56 //dc.DataType = dgvc.ValueType;//若需要限制導入時的數據類型則取消註釋,前提是DataGridView必須先綁定一個數據源那怕是空的DataTable
57 tb.Columns.Add(dc);
58 }
59 }
60
61 //根據Excel的行逐一對上面構造的DataTable的列進行賦值
62 foreach (DataRow excelRow in ds.Tables[0].Rows)
63 {
64 int i = 0;
65 DataRow dr = tb.NewRow();
66 foreach (DataColumn dc in tb.Columns)
67 {
68 dr[dc] = excelRow[i];
69 i++;
70 }
71 tb.Rows.Add(dr);
72 }
73 //在DataGridView中顯示導入的數據
74 dgv.DataSource = tb;
75 }
76 #endregion
77
78
79 #region button_export_Click
80 private void button_export_Click(object sender, EventArgs e)
81 {
82 if (null != this.dataGridView_files.CurrentCell)
83 {
84 if (SaveDataGireViewtoExcel())
85 {
86 MessageBox.Show("導出成功");
87 }
88 else
89 MessageBox.Show("導出失敗");
90 }
91 else
92 MessageBox.Show("沒有數據需要導出!");
93
94 }
95 #endregion
96
Q1:Excel中有列頭,如果需要導入,可把HDR設置爲NO,否則,設置爲NO
Q2:當把數據導入到Excel時,怎麼把“EXCEL.exe”關閉?