C#winForm导出excel
来源:互联网 发布:vim写c语言 编辑:程序博客网 时间:2024/06/05 13:28
//引用using System.Windows.Forms;using System.Data.OleDb;SaveFileDialog sfd = new SaveFileDialog();sfd.Filter = "Excel file(*.xls)|*.xls";sfd.Title = CliUtils.GetMessage("exporttitle");sfd.AddExtension = true;if (sfd.ShowDialog() == DialogResult.OK){ ExportExcel(sfd.FileName);}private void ExportExcel(string path) { //根据模板导出 string _fileName = string.Format(@"{0}\{1}", Application.StartupPath, "ImportTemplate.xls"); if (!File.Exists(_fileName)) { MessageBox.Show("客户端找不到导出模板文件"); return; } try { File.Copy(_fileName, path, true); } catch { MessageBox.Show(CliUtils.GetMessage("exportuse")); return; } string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;'";//IMEX=1 OleDbConnection OleConn = new OleDbConnection(strConn); OleConn.Open(); OleDbCommand comm; int count = 0; try { for (int i = 0; i < dataSet1.Tables[1].Rows.Count; i++) { string sql = string.Format(" Insert into [Sheet1$] values ('{0}',{1}) ", new object[]{ dataSet1.Tables[1].Rows[i]["value"],dataSet1.Tables[1].Rows[i]["qty"]}); comm = new OleDbCommand(sql, OleConn); comm.ExecuteNonQuery(); count++; } } catch { MessageBox.Show("文件正在被使用"); return; } finally { OleConn.Close(); } if (count > 0) { this.Close(); } }