在C#2010和.Net 4.0中将Datagridview导出到Excel [英] Export Datagridview to Excel in C# 2010 and .Net 4.0

查看:54
本文介绍了在C#2010和.Net 4.0中将Datagridview导出到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想将Datagridview导出到C#2010和.Net 4.0中的Excel
请举一个清晰的例子来帮助我.
谢谢

Hi
I want to Export Datagridview to Excel in C# 2010 and .Net 4.0
Please Help me by a clear Example.
Thanks

推荐答案

您必须手动将数据从网格移动到excel工作表.以下代码是我前一段时间用来执行此操作的代码.并非完全来自网格.其他人可能有执行此操作的代码.您必须根据需要进行自定义:
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>


这篇关于在C#2010和.Net 4.0中将Datagridview导出到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆