/// <Summary>
/// Import all data in DataSet into Excel.
/// You need to add COM: Microsoft Excel Object Library.
/// Using Excel;
/// </Summary>
/// <Param name = "filePath"> </param>
/// <Param name = "ds"> </param>
Public static void ExportToExcel (string filePath, DataSet ds)
{
Object oMissing = System. Reflection. Missing. Value;
Excel. ApplicationClass xlApp = new Excel. ApplicationClass ();
Try
{
// Open an Excel file. The following are Office 2000.
Excel. Workbook xlWorkbook = xlApp. Workbooks. Open (filePath, oMissing,
OMissing,
OMissing );
Excel. Worksheet xlWorksheet;
// Loop all DataTable
For (int I = 0; I <ds. Tables. Count; I ++)
{
// Add a new Sheet.
XlWorksheet = (Excel. Worksheet) xlWorkbook. Worksheets. Add (oMissing, oMissing, 1, oMissing );
// Use TableName as the newly added Sheet name.
XlWorksheet. Name = ds. Tables [I]. TableName;
// Retrieve all values in this able and store them in stringBuffer.
String stringBuffer = "";
For (int j = 0; j <ds. Tables [I]. Rows. Count; j ++)
{
For (int k = 0; k <ds. Tables [I]. Columns. Count; k ++)
{
StringBuffer + = ds. Tables [I]. Rows [j] [k]. ToString ();
If (k <ds. Tables [I]. Columns. Count-1)
StringBuffer + = "";
}
StringBuffer + = "";
}
// Use the system clipboard
System. Windows. Forms. Clipboard. SetDataObject ("");
// Place the stringBuffer into the clipboard.
System. Windows. Forms. Clipboard. SetDataObject (stringBuffer );
// Select the first cell on the sheet page
(Excel. Range) xlWorksheet. Cells [1, 1]). Select ();
// Paste!
XlWorksheet. Paste (oMissing, oMissing );
// Clear the system clipboard.
System. Windows. Forms. Clipboard. SetDataObject ("");
}
// Save and close the workbook.
XlWorkbook. Close (Excel. XlSaveAction. xlSaveChanges, oMissing, oMissing );
System. Runtime. InteropServices. Marshal. ReleaseComObject (xlWorkbook );
XlWorkbook = null;
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
Finally
{
// Release...
XlApp. Quit ();
System. Runtime. InteropServices. Marshal. ReleaseComObject (xlApp );
XlApp = null;
GC. Collect ();
}
}