问题
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