2010-09-08 69 views
0

我有一個任務將數據集數據轉儲到Excel WorkBook.Suppose如果有多個表,那麼我必須動態創建更多WorkSheet。爲此,我做了一個小應用程序。但是我被卡住了創建no WorkSheets.Could任何人都可以幫我嗎?下面是代碼如何將數據轉儲到ExcelWorkBook中?

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

試試這個ExportHelper。本文清楚地說明了如何在Excel中將包含多個表的數據集導出到多個工作表中。

相關問題