Asp.net calls the excel component

Source: Internet
Author: User
How does Asp.net call Excel?

1. Reference Microsoft. Office. Interop. Excel. dll, automatically packaged as Interop. Microsoft. Office. Interop. Excel. dll

2. Code:

/// <Summary>

/// Generate an excel report

/// </Summary>

Private void CreateExcelReport ()

{

String xlTemplateFullPath = Server. MapPath ("~ /Function/Business/ExcelTemplate/OTOCFPY.xls ");

String xlSavePath = Server. MapPath ("~ /Function/Business/ExcelReport ");

_ Application xlApp = null;

 

_ Workbook xlWorkbook = null;

 

_ Worksheet xlWorksheet = null;

 

 

 

System. Reflection. Missing oMissing = System. Reflection. Missing. Value;

 

Try

{

XlApp = new ApplicationClass ();

XlWorkbook = xlApp. Workbooks. Open (xlTemplateFullPath,

OMissing,

OMissing,

OMissing,

OMissing,

OMissing,

OMissing,

OMissing,

OMissing,

OMissing,

OMissing,

OMissing,

OMissing,

OMissing,

OMissing );

XlWorksheet = (Worksheet) xlWorkbook. Worksheets [1];

 

XlSavePath = Path. Combine (xlSavePath, DateTime. Now. Ticks. ToString ());

 

// Write excel Data

WriteData (xlWorksheet );

 

XlWorkbook. SaveAs (xlSavePath, oMissing,

 

OMissing, Microsoft. Office. Interop. Excel. XlSaveAsAccessMode. xlShared, oMissing,

 


OMissing, oMissing );

XlApp. Visible = true;

XlApp. Quit ();

// Send an excel file to the client

Response. Clear ();

Response. Buffer = true;

Response. ContentType = "application/ms-excel ";

Response. AppendHeader ("Content-Disposition", "attachment?filename=todaydownlist.xls ");

System. IO. FileInfo fileInfo = new FileInfo (xlSavePath + ". xls ");

Response. AddHeader ("Content-Length", fileInfo. Length. ToString ());

Response. WriteFile (fileInfo. FullName );

Response. End ();

}

Catch (Exception ex)

{

Response. Write (ex. Message );

}

 

Finally

{

 

System. Runtime. InteropServices. Marshal. ReleaseComObject (xlApp );

 

XlApp = null;

 

GC. Collect ();

 

}

}

Notes

Excel used upBe sure to release excel later

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.