How to import data in Datatable directly to an Excel template

Source: Internet
Author: User
A row and a column. Here is a prompt:
Using Microsoft. Office. Core;
Using Microsoft. Office. Interop. Excel;
...
...
Microsoft. Office. Interop. Excel. Application myExcel = new Microsoft. Office. Interop. Excel. Application ();
MyExcel. Application. Workbooks. Add (true );
MyExcel. Visible = true;
..
..
For (int row = 0; row <= this. ds. Tables [0]. Rows. Count-1; row ++)
{
For (int col = 0; col <= this. ds. Tables [0]. Columns. Count-1; col ++)
{
MyExcel. Cells [row + 4, col + 1] = "'" + ds. Tables [0]. Rows [row]. ItemArray [col]. ToString ();
}
}

This is to bind the data on the able directly to the datagird, and then download the data from it to the excel file.
Private void btnDownLoad_Click (object sender, System. EventArgs e)
{
If (this. dg. Items. Count> 0)
{
Response. Clear ();
Response. Buffer = true;
Response. Charset = "GB2312 ";
Response. AppendHeader ("Content-Disposition", "attachment?filename=filename.xls ");
Response. ContentEncoding = System. Text. Encoding. GetEncoding ("GB2312"); // set the output stream to simplified Chinese
Response. ContentType = "application/ms-excel"; // set the output file type to an excel file.
This. EnableViewState = false;
CultureInfo myCItrad = new CultureInfo ("ZH-CN", true );
HtmlGenericControl div = new HtmlGenericControl ();
System. IO. StringWriter oStringWriter = new System. IO. StringWriter (myCItrad );
Div. InnerHtml = oStringWriter. ToString ();
System. Web. UI. HtmlTextWriter oHtmlTextWriter = new System. Web. UI. HtmlTextWriter (oStringWriter );
This. dgRoleMenu. RenderControl (oHtmlTextWriter );
Div. InnerHtml = oStringWriter. ToString ();
Response. Write (div. InnerText );
Response. End ();
} Else return;
}

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.