C # Imports data from SQL database into Excel and imports Excel into the SQL database

Source: Internet
Author: User
Tags import database

In real-world development, we often encounter the need to transform data into SQL, or import SQL data from a database table into Excel. The code is as follows: codeusing system;using system.collections.generic;using system.componentmodel;using System.Data;using System.drawing;using system.linq;using system.text;using system.windows.forms;using GemBox.ExcelLite;using System.data.sqlclient;using system.data.oledb;using system.collections;using system.io;namespace Encryption{Public Partial class Exceldemo:form {private static string _filepath = String. Empty; Public Exceldemo () {InitializeComponent (); Binduser (); } ////// binding Data ///private void Binduser () {String sql = "SELECT * from Users"; DataTable dt = DBHELPERSQL.QUERYTB (SQL); Datagridview1.datasource = DT; } ////// Import the data from the Users table into Excel //private void Btnexcelin_click (object sender, EventArgs e) {excelfile excelfile = new Excelfile (); Excelworksheet sheet = excelFile.Worksheets.Add ("Users"); int columns = DataGridView1.Columns.Count; int rows = DataGridView1.Rows.Count; for (int j = 0; j < columns; J + +) {sheet. Cells[0, J]. Value = Datagridview1.columns[j]. HeaderText; } for (int i = 1, i < rows; i++) {for (int j = 0; j < columns; J + +) {sheet. Cells[i, J]. Value = Datagridview1[j, i-1]. Value.tostring (). Trim (); }} Excelfile.savexls ("./users.xls"); MessageBox.Show ("Build succeeded"); } ////// Select an Excel file to import data into the SQL database ///private void Btnchoose_click (object sender, EventArgs e) {using (openfiledialog Dialog = new OpenFileDialog ()) {DIALOG.M Ultiselect = true; if (dialog. ShowDialog () = = DialogResult.OK) {try {txtpath.text = dialog. FileName; } Catch {}}}}///// import data from Excel into SQL database ///private void Btnexcelout_click (object sender, EventArgs e) {DataSet ds=importfromexcel (TxtPath.Text.Trim ()); DataTable dt = ds. Tables[0]; try {string strinsertcomm; for (int i = 0; i < dt. Rows.Count; i++) {Strinsertcomm = ""; Strinsertcomm = "Insert into NewUsers (loginnum,username,password,email,userhead,sex,bloodtype,birthplace,userlevel , Education,occupational,contact,[profile]) "; Strinsertcomm + = "VALUES ("; for (int j = 1; j < dt. Columns.count; J + +) {if (J > 1) {Strinsertcomm + = ", '" + dt. ROWS[I][J]. ToString (). Trim () + "'";} else {Strinsertcomm + = "'" + dt. ROWS[I][J]. ToString (). Trim () + "'";}} Strinsertcomm + = ")"; Dbhelpersql.executesql (Strinsertcomm); }} catch (Exception ex) {MessageBox.Show (ex). Message); }} #region Excel Import SQL database////// get an Excel data Table list ///// public static ArrayList Getexceltables (string FilePath) {//Excel schema is stored in data System.Data.DataTable dt = new System.Data.Data Table (); ArrayList tableslist = new ArrayList (); if (file.exists (FilePath)) {using (OleDbConnection conn = new OleDbConnection ("Provider=microsoft.jet." + "oledb.4.0; Extended properties=\ "Excel 8.0\";D ata source= "+ FilePath) {try {conn. Open (); DT = conn. GetOleDbSchemaTable (OleDbSchemaGuid.Tables, new object[] {null, NULL, NULL, "TABLE"}); } catch (Exception exp) {MessageBox.Show (exp. Message); }//Get data table number int tablecount = dt. Rows.Count; for (int i = 0; i < tablecount; i = i + 2) {string tablename = dt. ROWS[I][2]. ToString (). Trim (). TrimEnd (' $ '); if (Tableslist.indexof (tablename) < 0) {Tableslist.add (tablename);}} }} return tableslist; } //////import Excel Datasheet to DataTable (first row as header)////// public static System.Data.DataSet FillDataSet (string FilePath) {if (! File.exists (FilePath)) {throw new Exception ("Excel file does not exist! "); } ArrayList tablelist = new ArrayList (); Tablelist = Getexceltables (FilePath); if (tablelist.count <= 0) {return null;} System.Data.DataTable table; System.Data.DataSet ds = new DataSet (); OleDbConnection dbcon = new OleDbConnection (@ "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + FilePath + "; Extended Properties=excel 8.0 "); try {if (Dbcon. state = = connectionstate.closed) {Dbcon. Open (); } for (int i = 0; i < Tablelist.count; i++) {string dtname = Tablelist[i]. ToString (); try {OleDbCommand cmd = new OleDbCommand ("SELECT * FROM [" + Dtname + "$]", Dbcon); OleDbDataAdapter adapter = new OleDbDataAdapter (cmd); Table = new DataTable (dtname); Adapter. Fill (table); Ds. Tables.add (table); } catch (Exception exp) {MessageBox.Show (exp. Message); }}} finally {if (Dbcon. state = = ConnectionState.Open) {Dbcon. Close (); }} return DS; } ////// Excel Import Database ////// public static DataSet Importfromexcel (string FilePath) {return filldataset (FilePath);} #endregion}} Data from SQL to Excel takes advantage of GemBox.ExcelLite.dll, which can be downloaded online. Code is very simple, I hope you have any better ways to share out Ah! Sometimes it may be necessary to encrypt the imported and exported data, just define an encryption function, and then encrypt the data in turn OK.

C # Imports data from SQL database into Excel and imports Excel into the SQL database

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.