wpf中将数据导出为Excel

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

     try
        {
          excelApp.Visible = false;

          //Cria Planilha
          Workbook excelWB = excelApp.Workbooks.Add(System.Type.Missing);

          //Cria Worksheet
          Worksheet excelWS = (Worksheet)excelWB.Worksheets[1];

          Range celulas = null;
          celulas = excelWS.get_Range("A1", System.Type.Missing);
         
          //Laço para ler todas as linhas e colunas do grid
          for (int i = 0; i < ((System.Data.DataTable)(dataGrid2.DataContext)).Rows.Count; i++)
          {
            for (int j = 0; j < ((System.Data.DataTable)(dataGrid2.DataContext)).Columns.Count; j++)
            {
              //Insere valores das células do grid na célula do excel
              celulas.get_Offset(i, j).Cells.Value2 = ((System.Data.DataTable)(dataGrid2.DataContext)).Rows[i][j].ToString();
            }
          }

          excelApp.ActiveWorkbook.RefreshAll();
          excelApp.Workbooks.Application.ActiveWorkbook.RefreshAll();

          //Salva Arquivo
          excelWB.SaveAs(txtArmazenagem.Text + "//" + txtNomeArquivoArmazenagem.Text + ".xls", XlSaveAction.xlSaveChanges, System.Type.Missing, System.Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
          excelWB.Close(false, null, null);
        }
        catch (Exception ex)
        {
          MessageBoxResult result = MessageBox.Show(ex.Message);
          //throw ex;
        }
        finally
        {
          excelApp.Quit();
          MessageBoxResult result = MessageBox.Show("Exportação concluida com sucesso.");
          txtArmazenagem.Text = "";
          txtNomeArquivoArmazenagem.Text = "";
          dataGrid2.DataContext = null;
        }

转载于:https://www.cnblogs.com/liancs/archive/2011/05/11/3879318.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值