DataGridView导出数据到Excel中,可以导出当前页和全部数据:
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
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:
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
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”关闭?