Import data from SQL Server to excel (C #)

Source: Internet
Author: User

Source: http://www.csyh.com
Although DTs in SQL Server can also import data into excel, it is better to useProgramFlexible,
Main ProgramCodeIn the button function. Applicable to the read data section of report development :)
I deleted a lot of junk code from the original program, leaving only the code that mainly works.

// Add namespace
Using System. Data;
Using System. Data. sqlclient;


// The definition method getdata () returns a data table.
Private System. Data. datatable getdata ()
{
Sqlconnection Conn =   New Sqlconnection ( @" Server = pxgd2; initial catalog = Pingxiang; uid = sa; Pwd =; " );
Sqldataadapter Adapter =   New Sqldataadapter ( " Select username, port occupied by mongost_port, home_address residential address, ip_address

IP address, phone number, addtime activation date from userinfo where 1_st_port = 1 Or catalyst_port = '' Order by ip_address DESC " , Conn );

Dataset DS =   New Dataset ();
Try
  {
Adapter. Fill (DS,"Customer");
}
Catch (Exception ex)
  {
MessageBox. Show (ex. tostring ());
}
Return DS. Tables [ 0 ];
}

// Button
Private   Void Button#click ( Object Sender, system. eventargs E)
{
Excel. Application Excel =   New Excel. Application ();
Int Rowindex = 1 ;
Int Colindex = 0 ;

Excel. application. workbooks. Add ( True );

Datatable table = Getdata ();

// Assign the column name of the obtained table to the cell.
Foreach (Datacolumn col In Table. columns)
{
Colindex++;
Excel. cells [1, Colindex]=Col. columnname;
}

// Process data in the same way
Foreach (Datarow row In Table. Rows)
  {
Rowindex ++ ;
Colindex = 0 ;
Foreach (Datacolumn col In Table. columns)
{
Colindex++;
Excel. cells [rowindex, colindex]=Row [col. columnname]. tostring ();
}
}
// Invisible, that is, background processing
Excel. Visible = True ;
}
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.