C # Simple operation in Excel-adapting: Simple interaction with DB numbers

Source: Internet
Author: User

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.IO;usingSystem.Data.OleDb;usingSystem.Data;usingSystem.Windows.Forms;namespacewmsclient{ Public classExcelhelper {//Excel into a dataset         Public StaticDataSet Exceltodataset () {DataSet DataSet=NewDataSet (); OpenFileDialog OFD=NewOpenFileDialog (); OFD. Filter="Excel Files (. xls) |*.xls| All Files (*. *) |*.*"; if(OFD. ShowDialog () = =DialogResult.OK) {stringstrFileName =OFD.                FileName; DataSet=Exceltodataset (strFileName); }            returnDataSet; }        //Excel into a dataset         Public StaticDataSet Exceltodataset (stringFilePath) {            if(!file.exists (filePath))Throw NewFileNotFoundException ("file does not exist"); BOOLisExcel2003 = Filepath.endswith (". xls"); stringConnectionString =string. Format (isExcel2003?"Provider=Microsoft.Jet.OLEDB.4.0;Data source={0}; Extended Properties=excel 8.0;"                : "Provider=microsoft.ace.oledb.12.0;data source={0}; Extended properties=\ "Excel 12.0 Xml; Hdr=yes\ "", FilePath); DataSet DS=NewDataSet (); using(OleDbConnection connection =NewOleDbConnection (connectionString)) {connection.                Open (); stringSheetName = connection. GetOleDbSchemaTable (OleDbSchemaGuid.Tables,NULL). rows[0][2]. ToString ().                Trim ();; stringCommandText ="SELECT * FROM ["+ SheetName +"]"; using(OleDbDataAdapter da =NewOleDbDataAdapter (CommandText, connection)) {da.                    Fill (DS); Connection.                Close (); }            }            returnds; }        //DataGridView the Excel         Public Static voidDatagridviewtoexcel (DataGridView dgv) {//Datatabletoexcel (DGV. DataSource as DataTable);//Use the source as a DataTableSaveFileDialog Dlg=NewSaveFileDialog (); Dlg. Filter="execl Files (*.xls) |*.xls"; Dlg. FilterIndex=0; Dlg. Restoredirectory=true; Dlg. Title="Save As Excel file"; if(DLG. ShowDialog () = =DialogResult.OK) {Stream mystream; MyStream=dlg.                OpenFile (); StreamWriter SW=NewStreamWriter (MyStream, System.Text.Encoding.Default); stringColumntitle =""; Try                {                    //write into the title column                     for(inti =0; I < DGV. ColumnCount; i++)                    {                        if(DGV. Columns[i]. Visible) {if(Columntitle = ="") {Columntitle="\""+ DGV. Columns[i]. HeaderText +"\""; }                            Else{columntitle+="\ t"+"\""+ DGV. Columns[i]. HeaderText +"\""; }}} SW.                    WriteLine (Columntitle); //write in a content column                     for(intj =0; J < DGV. Rows.Count; J + +)                    {                        stringColumnvalue ="";  for(inti =0; I < DGV. Columns.count; i++)                        {                            if(DGV. Columns[i]. Visible) {stringCellvalue = DGV. ROWS[J]. Cells[i]. Value = =NULL?"": DGV. ROWS[J]. Cells[i]. Formattedvalue.tostring (). Replace ("\"","'"); if(Columnvalue = ="") {Columnvalue="\""+ Cellvalue +"\""; }                                Else{Columnvalue+="\ t"+"\""+ Cellvalue +"\""; }}} SW.                    WriteLine (Columnvalue); }                }                Catch(Exception ex) {MessageBox.Show (ex).                ToString ()); }                finally{SW.                    Close ();                Mystream.close (); }            }        }        //DataTable leads out of Excel         Public Static voiddatatabletoexcel (DataTable table) {SaveFileDialog Dlg=NewSaveFileDialog (); Dlg. Filter="execl Files (*.xls) |*.xls"; Dlg. FilterIndex=0; Dlg. Restoredirectory=true; Dlg. Title="Save As Excel file"; if(DLG. ShowDialog () = =DialogResult.OK) {Stream mystream; MyStream=dlg.                OpenFile (); StreamWriter SW=NewStreamWriter (MyStream, System.Text.Encoding.Default); stringColumntitle =""; Try                {                    //write into the title column                     for(inti =0; I < table. Columns.count; i++)                    {                        if(Columntitle = ="") {Columntitle="\""+ table. Columns[i]. ColumnName +"\""; }                        Else{columntitle+="\ t"+"\""+ table. Columns[i]. ColumnName +"\""; }} SW.                    WriteLine (Columntitle); //write in a content column                     for(intj =0; J < table. Rows.Count; J + +)                    {                        stringColumnvalue ="";  for(inti =0; I < table. Columns.count; i++)                        {                            stringCellvalue = table. Rows[j][i] = = DBNull.Value?"": Table. Rows[j][i]. ToString (). Replace ("\"","'"); if(Columnvalue = ="") {Columnvalue="\""+ Cellvalue +"\""; }                            Else{Columnvalue+="\ t"+"\""+ Cellvalue +"\""; }} SW.                    WriteLine (Columnvalue); }                }                Catch(Exception ex) {MessageBox.Show (ex).                ToString ()); }                finally{SW.                    Close ();                Mystream.close (); }            }        }    }} 

C # Simple operation in Excel-adapting: Simple interaction with DB numbers

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.