Windows Forms 中 DataGridView 数据导入 导出 Excel

private void button1_Click(object sender, EventArgs e)
  {
  System.Windows.Forms.SaveFileDialog saveFileDlg = new SaveFileDialog();
  saveFileDlg.FileName = "报废信息";//默认文件名  
  saveFileDlg.DefaultExt = "xls";//默认后缀名  
  saveFileDlg.Filter = "Excel文件 (*.xls) |*.xls";

  if (saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  {
  try
  {
  doExport(saveFileDlg.FileName);
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message, "系统管理", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  }
  }
  }

  private void doExport(string strExcelFileName)
  {
  Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
  if (excel == null)
  throw new Exception("无法启动Excel,可能您的计算机尚未安装Excel");
  int rowIndex = 1;
  int colIndex = 0;

  excel.Application.Workbooks.Add(true);
  if (dgvTrafficCalc != null && dgvTrafficCalc.Rows.Count > 0)
  {
  for (int i = 0; i < dgvTrafficCalc.ColumnCount; i++)
  {
  colIndex++;
  excel.Cells[1, colIndex] = dgvTrafficCalc.Columns[i].Name;
  }
  foreach (DataGridViewRow row in dgvTrafficCalc.Rows)
  {
  rowIndex++;
  colIndex = 0;
  foreach (DataGridViewColumn col in dgvTrafficCalc.Columns)
  {
  colIndex++;
  excel.Rows.Cells[rowIndex, colIndex] = row.Cells[col.Name].Value != null ? row.Cells[col.Name].Value.ToString() : "";
  }
  }
  }

  excel.Visible = false;
  try
  {
  excel.ActiveWorkbook.SaveAs(strExcelFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel9795, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
  }
  catch (Exception ex)
  {
  throw ex;
  }
  excel.Quit();
  excel = null;

  GC.Collect();//垃圾回收  
  
  }
//导入

   
  string fileName = null;
  this.openFileDialog1.Filter = "Excle文件(*.xls)|*.xls";
  if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
  {
  fileName = this.openFileDialog1.FileName;
  string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + fileName + "';Extended Properties=Excel 8.0;";
  DataSet myDataset = new DataSet();
  OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
  try
  {
  da.Fill(myDataset);
  this.dgvTrafficCalc.DataSource = myDataset.Tables[0];
  }
  catch (Exception ex)
  {
  MessageBox.Show("读取文件错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值