Ado.net exports data to excel and provides download

Source: Internet
Author: User
Ado.net exports data to excel and provides download

Public String datatabletoexcel (datatable DT, string excelpath)
{
If (Dt = NULL)
{
Return "datatable cannot be blank ";
}

Int rows = DT. Rows. count;
Int Cols = DT. Columns. count;
Stringbuilder Sb;
String connstring;

If (rows = 0)
{
Return "no data ";
}

SB = new stringbuilder ();
Connstring = string. Format (connectionstring, excelpath );

// Generate the table creation script
SB. append ("create table ");
SB. append (Dt. tablename + "(");

For (INT I = 0; I {
If (I <Cols-1)
SB. append (string. Format ("{0} varchar,", DT. Columns [I]. columnname ));
Else
SB. append (string. Format ("{0} varchar)", DT. Columns [I]. columnname ));
}

Using (oledbconnection objconn = new oledbconnection (connstring ))
{
Oledbcommand objcmd = new oledbcommand ();
Objcmd. Connection = objconn;

Objcmd. commandtext = sb. tostring ();

Try
{
Objconn. open ();
Objcmd. executenonquery ();
}
Catch (exception E)
{
Return "failed to create table in Excel, error message:" + E. message;
}

Generate the insert data script # region generate the insert data script
SB. Remove (0, SB. Length );
SB. append ("insert ");
SB. append (Dt. tablename + "(");

For (INT I = 0; I {
If (I <Cols-1)
SB. append (Dt. Columns [I]. columnname + ",");
Else
SB. append (Dt. Columns [I]. columnname + ") values (");
}

For (INT I = 0; I {
If (I <Cols-1)
SB. append ("@" + dt. Columns [I]. columnname + ",");
Else
SB. append ("@" + dt. Columns [I]. columnname + ")");
}
# Endregion

// Create the INSERT command
Objcmd. commandtext = sb. tostring ();
Oledbparametercollection Param = objcmd. parameters;

For (INT I = 0; I {
Param. Add (New oledbparameter ("@" + dt. Columns [I]. columnname, oledbtype. varchar ));
}

// Traverse datatable to insert data into the new Excel File
Foreach (datarow row in DT. Rows)
{
For (INT I = 0; I {
Param [I]. value = row [I];
}

Objcmd. executenonquery ();
}

Return "data has been imported into excel ";
} // End using
}

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.