exporting selected cells from datagrigview to excel

梦想与她 提交于 2019-12-08 11:09:06

问题


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..


回答1:


This should work:

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



回答2:


You should also check out EPPlus it is a open source .net library that can read and write Excel 2007/2010 files using the Open Office Xml format. However, you can't read/write .xls files. I still prefer it over Microsoft.Office.Interop.Excel.



来源:https://stackoverflow.com/questions/12616539/exporting-selected-cells-from-datagrigview-to-excel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!