zoukankan      html  css  js  c++  java
  • 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;
            }

  • 相关阅读:
    mysql 迁移
    ubuntu 安装 mysql
    Ubuntu 常用命令
    ubuntu 安装 redis
    Ubuntu 文件移动
    题解 [NOI2014] 动物园
    项目管理实践【四】Bug跟踪管理【Bug Trace and Management】
    项目管理实践【五】自动编译和发布网站【Using Visual Studio with Source Control System to build and publish website automatically】
    项目管理实践【三】每日构建【Daily Build Using CruiseControl.NET and MSBuild】
    SQL Server修改表结构后批量更新所有视图
  • 原文地址:https://www.cnblogs.com/liancs/p/3879318.html
Copyright © 2011-2022 走看看