如何将数据转储到ExcelWorkBook? [英] How to dump the data into ExcelWorkBook?

查看:276
本文介绍了如何将数据转储到ExcelWorkBook?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务,将数据集数据转储到Excel WorkBook.Suppose如果有多个表,那么我必须动态创建更多的工作表。对我做了一个小应用程序。但我被困住创建没有WorkSheets。下面是代码

I have a task to dump the dataset data into Excel WorkBook.Suppose if have more than one table then i have to Create More WorkSheets dynamically.For that i did a small application.But i was stuckup with creating no of WorkSheets.Could anyone help me ?Below is the Code

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();
  }
}


推荐答案

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

Try this ExportHelper. This article clearly explains how to export a dataset with multiple table to multiple worksheets in excel.

这篇关于如何将数据转储到ExcelWorkBook?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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