/** // <Summary>
/// Import all data in dataset to excel
/// You need to add COM: Microsoft Excel Object Library
/// Using Excel;
/// </Summary>
/// <Param name = "filepath"> file path </param>
/// <Param name = "ds"> dataset to be stored </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,
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
System. Text. stringbuilder stringbuffer = new system. Text. stringbuilder ();
For (Int J = 0; j <Ds. Tables [I]. Rows. Count; j ++)
...{
For (int K = 0; k <Ds. Tables [I]. Columns. Count; k ++)
... {Stringbuffer. append (string) ds. Tables [I]. Rows [J] [k]);
If (k <Ds. Tables [I]. Columns. Count-1)
Stringbuffer. append ("/t ");
}
Stringbuffer. append ("/N ");
}
// Use the system clipboard
System. Windows. Forms. clipboard. setdataobject ("");
// Put stringbuffer into the clipboard
System. Windows. Forms. clipboard. setdataobject (stringbuffer );
// Select the first cell in the sheet page (subscript starts from 1)
(Excel. Range) xlworksheet. cells [1, 1]). Select ();
// Paste the content in the clipboard in sheet
Xlworksheet. paste (omissing, omissing );
// Clear the system clipboard
System. Windows. Forms. clipboard. setdataobject ("");
}
// Save and close this 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 the COM Object
Xlapp. Quit ();
System. runtime. interopservices. Marshal. releasecomobject (xlapp );
GC. Collect ();
}
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.