C # export the EXCEL function (you can modify it as needed)

Source: Internet
Author: User
// Export the Excel file
Private void exportexcel ()
{
Dataset DS = dtsselect; // Data Source
If (DS = NULL) return;

String savefilename = "";
Bool filesaved = false;
Savefiledialog savedialog = new savefiledialog ();
Savedialog. defaultext = "xls ";
Savedialog. Filter = "Excel file | *. xls ";
Savedialog. filename = "sheet1 ";
Savedialog. showdialog ();
Savefilename = savedialog. filename;
If (savefilename. indexof (":") <0) return; // canceled

Excel. Application xlapp = new excel. Application ();

If (xlapp = NULL)
{
MessageBox. Show ("an Excel object cannot be created, maybe your computer has not installed excel ");
Return;
}

Excel. workbooks = xlapp. workbooks;
Excel. Workbook workbook = workbooks. Add (Excel. xlwbatemplate. xlwbatworksheet );
Excel. worksheet = (Excel. worksheet) Workbook. worksheets [1]; // get sheet1
// Write Fields
For (INT I = 0; I <Ds. Tables [0]. Columns. Count; I ++)
{
Worksheet. cells [1, I + 1] = Ds. Tables [0]. Columns [I]. columnname;
}
// Write Value

For (INT r = 0; r <Ds. Tables [0]. Rows. Count; r ++)
{
For (INT I = 0; I <Ds. Tables [0]. Columns. Count; I ++)
{
Worksheet. cells [R + 2, I + 1] = Ds. Tables [0]. Rows [r] [I];
}
System. Windows. Forms. application. doevents ();
}
Worksheet. Columns. entirecolumn. autofit (); // adaptive column width.
If (cmbxtype. Text! = "Notification ")
{
Excel. Range Rg = worksheet. get_range (worksheet. cells [2, 2], Worksheet. cells [Ds. Tables

[0]. Rows. Count + 1, 2]);
RG. numberformat = "00000000 ";
}
If (savefilename! = "")
{
Try
{
Workbook. Saved = true;
Workbook. savecopyas (savefilename );
Filesaved = true;
}
Catch (exception ex)
{
Filesaved = false;
MessageBox. Show ("An error occurred while exporting the file. The file may be opened! \ N "+ ex. Message );
}
}
Else
{
Filesaved = false;
}
Xlapp. Quit ();
GC. Collect (); // forcibly destroy
If (filesaved & system. Io. file. exists (savefilename) system. Diagnostics. process. Start

(Savefilename); // enable exce

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.