Example of small Excel application in C #

Source: Internet
Author: User

Often used in Database SystemsExcel, Sometimes you need to useExcelAs a data source, sometimes you need to use the queried dataExcelWill be used continuously.Excel .....

First load the reference:

UsingMicrosoft. Office. InterOP. Excel;

Using Excelapplication= Microsoft. Office. InterOP. Excel.Application;

Note: If you have previously loaded using system. Data, note the following:

Instead of defining datatable table directly, instead of system. Data.Datatable tableOr perform another conversion, becauseExcelapplicationThere are also datatable classes,

Public static void dotoexcel (system. Data. datatable table)

{

Try

{

Excelapplication Excel = new excelapplication ();

Int rowindex = 1;

Int colindex = 0;

Excel. application. workbooks. Add (true );

Foreach (datacolumn Col in table. columns)

{

Colindex ++;

Excel. cells [1, colindex] = col. columnname;

}

Foreach (datarow row in table. Rows)

{

Rowindex ++;

Colindex = 0;

Foreach (datacolumn Col in table. columns)

{

Colindex ++;

Excel. cells [rowindex, colindex] = row [col. columnname]. tostring ();

}

}

Excel. Visible = false;

Savefiledialog Sf = new savefiledialog ();

SF. addextension = true;

SF. Filter = "Excel 2003 (*. xls) | *. xls |All files| *.*";

SF. Title ="ExportExcelSave";

If (SF. showdialog () = dialogresult. OK)

{

String filename = SF. filename;

Excel. activeworkbook. saveas (filename, Microsoft. office. interOP. excel. xlfileformat. xlexcel9795, null, null, false, false, Microsoft. office. interOP. excel. xlsaveasaccessmode. xlnochange, null, null );

Excel. Quit ();

Excel = NULL;

GC. Collect ();

MessageBox. Show ("Exported successfully!");

}

}

Catch (exception ex)

{

MessageBox. Show ("Export failed!");

Writelogtxt ("dotoexcel", Ex. Message );

}

}

# Endregion

}

In the preceding exampleSystem. Data. datatable tableConvertExcel,Col. columnnameAll will be the default, it is best to operateSystem. Data. datatable tableTime conversion, including statistical rows......

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.