Utionsoft-专业的WPF软件开发公司,欢迎您的萃垂青


专注WPF/Silverlight技术,此blog与大家分享技术文章相互学习进步.

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;
}

posted @ 2012-10-09 01:58  WPF外包公司——长年承接WPF外包项目  阅读(630)  评论(0编辑  收藏  举报

殊胜软件公司----长年承接WPF外包项目Silverlight外包项目,承接WPF项目Silverlight项目