public static bool DataGridViewToExcel(DataGridView dataGridView, bool isShowExcel)
{
int rowsQty = dataGridView.Rows.Count;
int colsQty = dataGridView.Columns.Count;
int colIndex = 0;
if (rowsQty == 0)
{
return false;
}
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
excel.Visible = isShowExcel;
foreach (DataGridViewColumn col in dataGridView.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.Name;
}
object[,] objData = new object[rowsQty, colsQty];
for (int r = 0; r < rowsQty; r++)
{
for (int c = 0; c < colsQty; c++)
{
objData[r, c] = dataGridView.Rows[r].Cells[c].Value;
}
}
Microsoft.Office.Interop.Excel.Range myRange;
myRange = worksheet.Range[excel.Cells[2, 1], excel.Cells[rowsQty + 1, colsQty]];
myRange.Value2 = objData;
,