C # use Excel to import and export data

Source: Internet
Author: User


// Import Excel , returns a dataset

Public dataset inputexcel (string path)
{
String strconn = "provider = Microsoft. Jet. oledb.4.0;" + "Data Source =" + path + ";" + "extended properties = Excel 8.0 ;";
Oledbconnection conn = new oledbconnection (strconn );
Conn. open ();
String strexcel = "";
Oledbdataadapter mycommand = NULL;
Dataset DS = NULL;
Strexcel = "select * from [sheet1 $]";
Mycommand = new oledbdataadapter (strexcel, strconn );
DS = new dataset ();
Mycommand. Fill (DS, "Table1 ");
Return Ds;
}


// Export Excel Document
Public bool outputexcel (string path)
{
Try
{
String strconn = "provider = Microsoft. Jet. oledb.4.0;" + "Data Source =" + path + ";" + "extended properties = Excel 8.0 ;";
Oledbconnection conn = new oledbconnection (strconn );
Conn. open ();
System. Data. oledb. oledbcommand cmd = new oledbcommand ();
Cmd. Connection = conn;
// Cmd. commandtext = "Update [sheet1 $] Set Name = '1970-01-01 'Where Employee ID =' Date '";
// Cmd. executenonquery ();
For (INT I = 0; I <fp2.sheets [0]. rowcount-1; I ++)
{
If (fp2.sheets [0]. cells [I, 0]. Text! = "")
{
Cmd. commandtext = "insert into [sheet1 $] ( Employee ID , Name , Department , Title , Date , Time ) Values ('"+ fp2.sheets [0]. cells [I, 0]. Text +"', '"+
Fp2.sheets [0]. cells [I, 1]. text + "','" + fp2.sheets [0]. cells [I, 2]. text + "','" + fp2.sheets [0]. cells [I, 3]. text +
"','" + Fp2.sheets [0]. cells [I, 4]. text + "','" + fp2.sheets [0]. cells [I, 5]. text + "')";
Cmd. executenonquery ();
}
}
Conn. Close ();
Return true;
}
Catch (system. Data. oledb. oledbexception ex)
{
System. Diagnostics. Debug. writeline (" Write Excel Error: "+ Ex. Message );
}
Return false;
}

 
 

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.