WPF中将DataGrid导出Excel

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

转载于:https://www.cnblogs.com/BeiJing-Net-DaiDai/p/3204892.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值