Asp. NET Background customization export Excel

Source: Internet
Author: User

About the export, belongs to the cliché, the following summarizes my own experience some of the export it.

1. Use the Excel component to export (you need to install Microsoft Office Excel).

Here is the code, hoping to help others.

1) Prepare the data source

//First create a datatabledatatable Dtsource =NewDataTable ();d tSource.Columns.Add ("Id");d TSource.Columns.Add ( "name" );d TSource.Columns.Add ( "description ");  

//Add some data to the DataTable
for (int i=0;i<10;i++) {
DataRow row = Dtsource.newrow ();
row["ID"]=i+1;
row["Name"]= "Tom and Jerry";
row["Description"]= "This is a classic cartoon, Cat and Mouse";
DtSource.Rows.Add (row);
} /span>

String filePath = HttpContext.Current.Server.MapPath ("~/upfiles/file/aa.xls");

2) Create an Excel object and add the data

// null;   // Create an Office object, or use the Microsoft.office.interop.excel._application
Excel = new Microsoft.Office.Interop.Excel.ApplicationClass ();
Excel. Workbooks.Add (TRUE);
int rowindex=1; Lines in Excel, starting with 1
int colindex=1; Columns in Excel, starting with 1
Add title
foreach (DataColumn col in Dtsource.columns) {
Excel. Cells[rowindex,colindex] = Col. ColumnName;
colindex++;
}
Add Table Contents
foreach (DataRow row in dtsource.rows) {
rowindex++;
Colindex = 1;
foreach (DataColumn col in Dtsource.columns) {
Excel. Cells[rowindex,colindex]=row[col. ColumnName]. ToString ();
colindex++;
}
}

Excel. ActiveWorkbook.SaveAs (FilePath, Missing.value,missing.value,missing.value,missing.value,missing.value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange
, Missing.value,missing.value,missing.value,missing.value,missing.value);

Excel. Quit ();
Excel = null;

3) generate the results as shown in

Asp. NET Background customization export Excel

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.