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 ;
}