Export Data to Excel
Hello. Based upon what year a user selects, the application is going out to a server and returning data. When I plus this into a gridview on the page, it works fine. The problem I am having is this: how do I take that returned data and turn it into an Excel document? Thanks in advance for the help.
Satish KathiPosted Nov 7, 2008, 3:54 PM
Here is the code to send data in a grid view to excel sheet
using
Excel = Microsoft.Office.Interop.Excel;private void button5_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
WriteToExcel(dataGridView1.Rows);
}
///
/// Writes DataGridViewRows' Data to Excel
///
///
public static void WriteToExcel(DataGridViewRowCollection dgvRows)
{
Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook excelWorkBook = excelApplication.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet excelWorkSheet = (Excel.Worksheet)excelWorkBook.ActiveSheet;
WriteColumnHeadersInWorkSheet(excelWorkSheet, dgvRows[0]);
int rowNum = 2;
foreach (DataGridViewRow row in dgvRows)
{
//Create New Sheet if reached max rows for a sheet
if (rowNum % excelWorkSheet.Rows.Count == 0)
{
excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets.Add(System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
WriteColumnHeadersInWorkSheet(excelWorkSheet, row);
rowNum = 2;
}
for (int colNum = 1; colNum <= row.Cells.Count; colNum++)
{
if (row.Cells[colNum - 1].Value == null)
continue;
if (row.Cells[colNum - 1].OwningColumn.ValueType == typeof(string)
|| row.Cells[colNum - 1].OwningColumn.ValueType == typeof(char)
|| row.Cells[colNum - 1].OwningColumn.ValueType == typeof(bool)
|| row.Cells[colNum - 1].OwningColumn.ValueType == typeof(DateTime))
excelWorkSheet.Cells[rowNum, colNum] = string.Concat("'", row.Cells[colNum - 1].Value.ToString());
else
excelWorkSheet.Cells[rowNum, colNum] = row.Cells[colNum - 1].Value.ToString();
}
rowNum++;
}
excelApplication.Visible = true;
excelWorkSheet.Visible = Excel.XlSheetVisibility.xlSheetVisible;
}
private static void WriteColumnHeadersInWorkSheet(Excel.Worksheet excelWorkSheet, DataGridViewRow dgvRow)
{
for (int colNum = 1; colNum <= dgvRow.Cells.Count; colNum++)
{
excelWorkSheet.Cells[1, colNum] = dgvRow.Cells[colNum - 1].OwningColumn.Name;
}
}
Hope this helps