Export dataset data to excel (ASP. NET/C #)

Source: Internet
Author: User
Actually, it is searched from the Internet... (learning ......)
// Export EXCEL from Dataset
Public void createexcel (Dataset ds, string typeid, string filename)
{
Httpresponse resp;
Resp = page. response;
Resp. contentencoding = system. Text. encoding. getencoding ("gb2312 ");
Resp. appendheader ("content-disposition", "attachment; filename =" + filename );
String colheaders = "", ls_item = "";
Int I = 0;

// Define the table object and row object, and use dataset to initialize the value.
Datatable dt = Ds. Tables [0];
Datarow [] myrow = DT. Select ("");
// When typeid = "1", the exported documents are in Excel format; When typeid = "2", the exported documents are in XML format.
If (typeid = "1 ")
{
// Obtain the titles of each column in the data table, separated by \ t, and a carriage return is added after the title of the last column.
For (I = 0; I <dt. Columns. Count; I ++)
{
If (I = dt. Columns. Count-1)
{
Colheaders + = DT. Columns [I]. Caption. tostring () + "\ n ";
}
Else
{
Colheaders + = DT. Columns [I]. Caption. tostring () + "\ t ";
}
}
// Write the obtained data to the HTTP output stream
Resp. Write (colHeaders );
// Process data row by row
Foreach (DataRow row in myRow)
{
// In the current row, data is obtained one by one, separated by \ t, and carriage return \ n is added at the end
For (I = 0; I <DT. Columns. Count; I ++)
{

If (I = DT. Columns. Count-1)
{
Ls_item + = row [I]. tostring () + "\ n ";
}
Else
{
Ls_item + = row [I]. tostring () + "\ t ";
}
}
// Write the data in the current row to the HTTP output stream, and leave ls_item empty for downstream data
Resp. Write (ls_item );
Ls_item = "";
}
}
Else
{
If (typeid = "2 ")
{
// Export XML data directly from dataset and write it to the HTTP output stream
Resp. Write (Ds. getxml ());
}
}
// Write the data in the buffer to the HTTP header document
Resp. End ();
}

Related Article

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.