如何将数据转储到ExcelWorkBook?

时间:2010-09-08 13:39:47

标签: c#-4.0 datatable export-to-excel

我有一项任务是将数据集数据转储到Excel WorkBook.Suppose如果有多个表,那么我必须动态创建更多的工作表。为此我做了一个小应用程序。但是我没有创建没有WorkSheets。任何人都可以帮助我吗?以下是代码

private void btn_export2excel_Click(object sender, EventArgs e)
{
  DataSet ds = new DataSet();
  ds.Tables.Add("Categories");
  ds.Tables.Add("Employee");

  try
  {
    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet[] xlWorkSheet = new Excel.Worksheet[2];
    object misValue = System.Reflection.Missing.Value;
    xlApp = new Excel.Application();
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet[0] = (Excel.Worksheet) xlWorkBook.Worksheets.get_Item(1);
    xlWorkSheet[1] = (Excel.Worksheet) xlWorkBook.Worksheets.get_Item(1);
    xlWorkSheet[0].Cells[1, 1] = "www.google.com";
    xlWorkSheet[1].Cells[1, 1] = "www.yahoo.com";
    xlWorkBook.SaveAs("Sample.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
                      Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();
    releaseObject(xlWorkSheet[0]);
    releaseObject(xlWorkSheet[1]);
    releaseObject(xlWorkBook);
    releaseObject(xlApp);
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Message from form");
  }
  finally
  {
    GC.Collect();
  }
}

private void releaseObject(object obj)
{
  try
  {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
    obj = null;
  }
  catch (Exception ex)
  {
    obj = null;
    MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
  }
  finally
  {
    GC.Collect();
  }
}

1 个答案:

答案 0 :(得分:1)

试试这个ExportHelper。本文清楚地解释了如何将具有多个表的数据集导出到excel中的多个工作表。