Export datatable to excel

Source: Internet
Author: User
This section describes how to import data from a able table to an Excel worksheet. First, bind the data in the able data table to the gridview, and then add the data in the gridview to the Excel format. Instance Code String sconnectionstring; // declare a string // connect to the database string and connect to the xbmis database. The username is sasconnectionstring = "Data Source = .; initial catalog = xbmis; user id = sa; "; // create the sqlconnection database connection object sqlconnection conn = new sqlconnection (sconnectionstring); // open connconn. open (); // SQL statement to retrieve all the data in the t_yongh table string commandstring = "select bianh as number, zhucyhm as registration name, xingm as name, xingb as gender from t_yongh "; sqldataadapter dataadapter = new sqldataadapter (commandstring, Conn); ds_datatable DS = new ds_datatable (); // fill the dataset dataadapter. fill (DS, "yongh"); datatable datatable1 = Ds. tables ["yongh"]; response. clear (); response. buffer = true; // response. contenttype = "application/vnd. MS-excel "; response. contenttype = "application/vnd. MS-word "; response. contentencoding = system. text. encoding. utf8; response. charset = ""; this. enableviewstate = false; stringwriter ostringwriter = new stringwriter (); htmltextwriter ohtmltextwriter = new htmltextwriter (ostringwriter); DataGrid DG = new DataGrid (); DG. datasource = datatable1; // return datatabledg. databind (); DG. rendercontrol (ohtmltextwriter); response. write (ostringwriter. tostring (); response. end ();

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.