ASP. NET export Excel

Source: Internet
Author: User
Use the. NET Excel component to export an Excel file,

/// <Summary>
/// Export Excel
/// </Summary>
/// <Param name = "Source"> data to be exported </param>
/// <Param name = "exportfullpath"> export the full path of an Excel file </param>
/// <Param name = "hasheadline"> if true, the header is generated. </param>
Private void exportexcel (datatable source, string exportfullpath, bool hasheadline)
{

# Region export using the. NET Excel component

Application objexcel = new application ();
If (objexcel = NULL)
{
Throw new exception ("error: You must install Microsoft Excel application! ");
}

// Create an Excel file (not saved, no file name)
Workbooks objworkbooks = objexcel. workbooks;
_ Workbook objworkbook = objworkbooks. Add (xlwbatemplate. xlwbatworksheet); // sheet1 is created by default.

// Get sheet1
Sheets objsheets = objworkbook. worksheets;
_ Worksheet objworksheet = (_ worksheet) objsheets. get_item (1 );

// Write the title
Int intdatabeginrow = 1;
If (hasheadline)
{
For (INT I = 0; I <source. Columns. Count; I ++)
{
Objworksheet. cells [1, I + 1] = source. Columns [I]. columnname. Trim ();
}

// Add 1 to the start row of the data
Intdatabeginrow ++;
}

// Write data. The Excel Index starts from 1.
For (Int J = 0; j <source. Rows. Count; j ++)
{
For (int K = 0; k <source. Columns. Count; k ++)
{
Objworksheet. cells [J + intdatabeginrow, k + 1] = source. Rows [J] [K]. tostring ();
}
}
Objworksheet. hyperlinks. Delete (); // remove the hyperchain

// Save the file (if you use objworkbook. saveas, it will be incompatible with excel2000 and excelxp)
Objworkbook. _ saveas (exportfullpath, missing. value, missing. value, missing. value, missing. value, missing. value, xlsaveasaccessmode. xlnochange, missing. value, missing. value, missing. value, missing. value );

// Close the file and release the resource
Objworkbook. Close (false, exportfullpath, false );
Objexcel = NULL;

# Endregion
}

Call exportexcel directly.

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.