WPF中将DataGrid导出Excel

时间:2021-11-06 16:01:49

int number = 1;
private void MenuItem_Click(object sender, RoutedEventArgs e)
{

#region
string path = "F:\\";
string fileName = "Excel文件名称.xls";
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
try
{
Workbook excelWB = app.Workbooks.Add(System.Type.Missing);

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

Range celulas = null;
celulas = excelWS.get_Range("A1", System.Type.Missing);

for (int i = 0; i < (GetTable()).Rows.Count; i++)
{
for (int j = 0; j < (GetTable()).Columns.Count; j++)
{
//Insere valores das células do grid na célula do excel
celulas.get_Offset(i, j).Cells.Value2 = (GetTable()).Rows[i][j].ToString();
}
}

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

//Salva Arquivo
if (File.Exists(path + fileName))
{
fileName = fileName.Insert(fileName.LastIndexOf('.'), number++.ToString());
}
excelWB.SaveAs(path+fileName, 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 = System.Windows.MessageBox.Show(ex.Message);
//throw ex;
}
finally
{
app.Quit();
MessageBoxResult result = System.Windows.MessageBox.Show("导出完成!路径为:" + (path + fileName).ToString());
dgPipeNetwork.DataContext = null;
}
#endregion

}

WPF、AE技术交流群:94234450  

群链接:http://wp.qq.com/wpa/qunwpa?idkey=14e3d476b4a53a3a1502183e5a384d94b8be74b7510c0a76e67c4dec61f23781