将所选单元格从datagrigview导出到excel [英] exporting selected cells from datagrigview to excel

查看:216
本文介绍了将所选单元格从datagrigview导出到excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉您如何将所选单元格从datagridview导出为ex​​cel?选择应通过单元格单击事件,并在单击按钮时将其导出到excel文件。任何人都可以帮助我..

Can anyone tell how to export the selected cells from a datagridview to excel ? The selection should be through a cell click event and the export it to the excel file when a button is clicked. Can anyone help me out..

推荐答案

这应该可以工作:

using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

var rows = dataGridView1.Rows.Count;
var columns = dataGridView1.Columns.Count;

var dataAsObjectArray = new object[rows,columns];

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < columns; j++)
    {
        dataAsObjectArray[i, j] = dataGridView1.Rows[i].Cells[j];
    }
}

Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];

Excel.Range range  = worksheet.Range[rows, columns];
range.Value = dataAsObjectArray;

workbook.SaveAs(@"C:\whatever.xlsx");
workbook.Close();

Marshal.ReleaseComObject(application);

这篇关于将所选单元格从datagrigview导出到excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆