Click here to Skip to main content
15,909,051 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I want to Export Datagridview to Excel in C# 2010 and .Net 4.0
Please Help me by a clear Example.
Thanks
Posted

1 solution

You have to manually move the data from the grid to the excel sheet. The following code is some that I used to do this a while ago. Not exactly fro a grid. Somebody else may have code to do this. You will have to customize to your need:
private static void Excel(string fileName, List<idirectoryinventorydatacollector> list)
{
  Excel.Application xlApp;
  Excel.Workbook xlWorkBook;
  Excel.Worksheet xlWorkSheet;
  int rowcounter = 0;

  try
  {
    xlApp = new Excel.Application();
    xlWorkBook = xlApp.Workbooks.Add();

    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    ExcelTitleRow(list[0], 1, xlWorkSheet);

    int row = 2;
    foreach (var item in list)
    {
      ExcelFillRow(item, row++, xlWorkSheet);
      rowcounter++;
    }
    xlWorkBook.SaveAs(fileName);
    xlWorkBook.Close();
    xlApp.Quit();
  }
  catch (AccessViolationException)
  {
    System.Windows.Forms.MessageBox.Show(
       "Have encountered access violation. This could be issue with Excel 2000 if that is only version installed on computer",
       "Access Violation");
  }
  catch (Exception)
  {
    System.Windows.Forms.MessageBox.Show("Unknown error",
       "Unknown error");
  }
}

private static void ExcelFillRow(IDirectoryInventoryDataCollector item, int row, Excel.Worksheet sheet)
{
  sheet.Cells[row, item.Level] = item.Name;
  int column = item.MaxLevel;
  foreach (var property in item.GetProperties())
  {
    sheet.Cells[row, column++] = property;
  }
}

private static void ExcelTitleRow(IDirectoryInventoryDataCollector item, int row, Excel.Worksheet sheet)
{
  sheet.Cells[row, 1] = "Name";
  int column = item.MaxLevel;
  foreach (var property in item.GetPropertyNames())
  {
    sheet.Cells[row, column++] = property;
  }
}</idirectoryinventorydatacollector>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900