程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#數據庫數據導入導出系列之四 WinForm數據庫導入導出到Excel

C#數據庫數據導入導出系列之四 WinForm數據庫導入導出到Excel

編輯:C#入門知識

 

在日常的項目中,Excel,Word,txt等格式的數據導入到數據庫中是很常見的,我在這裡做一下總結

 

這裡將分為Asp.net導入Sql Server,Oracle數據庫和WinForm導入Sql Server,Oracle數據庫。

 

這裡將的數據庫數據庫導入導出,其實對Sql Server 和Oracle都是通用的

 

如果使用ADO.Net連接Oracle數據庫,需要在引用裡添加“System.Data.OracleClient ”,其他方面與連接Sql Server數據庫是一樣的

 

SqlConnection cn = new SqlConnection();

OracleConnection oraleCn = new OracleConnection();

 

如果使用諸如Ibatis等持久層框架的話,唯一的區別就是在數據庫連接語句上的差別而已。下面是兩個例子

 

Oracle:Data Source=192.168.0.11/Contact;User ID=system;Password=ss;Unicode=True

 

Sql Server:Data Source=Contact;Server=localhost;uid=sa;pwd=ss

 

1,數據庫導出到Excel

 

先看界面

\

 

 

然後是代碼

 

 

using 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 System.Diagnostics; 

using Microsoft.Office.Interop.Excel; 

using System.Reflection; 

using System.IO; 

using System.Data.SqlClient; 

using System.Data.OracleClient; 

 

namespace SqlServer__Excel 

    public partial class SqlDB_To_Excel : Form 

    { 

        public SqlDB_To_Excel() 

        { 

            InitializeComponent(); 

        } 

 

        private Microsoft.Office.Interop.Excel.Application myExcel = null; 

 

        private void button1_Click(object sender, EventArgs e) 

        { 

            print(dataGridView1); 

        } 

 

        public void print(DataGridView dataGridView1) 

        { 

            //導出到execl    

            try 

            { 

                SaveFileDialog saveFileDialog = new SaveFileDialog(); 

                saveFileDialog.Filter = "導出Excel (*.xls)|*.xls"; 

                saveFileDialog.FilterIndex = 0; 

                saveFileDialog.RestoreDirectory = true; 

                saveFileDialog.CreatePrompt = true; 

                saveFileDialog.Title = "導出文件保存路徑"; 

                saveFileDialog.ShowDialog(); 

                string strName = saveFileDialog.FileName; 

                if(strName.Length != 0) 

                { 

                    //沒有數據的話就不往下執行    

                    if(dataGridView1.Rows.Count == 0) 

                        return; 

 

                    // toolStripProgressBar1.Visible = true; 

                    System.Reflection.Missing miss = System.Reflection.Missing.Value; 

                    //實例化一個Excel.Application對象 

                    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 

                    excel.Application.Workbooks.Add(true); 

                    excel.Visible = false;//若是true,則在導出的時候會顯示EXcel界面。 

                    if(excel == null) 

                    { 

                        MessageBox.Show("EXCEL無法啟動!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); 

                        return; 

                    } 

                    Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks; 

                    Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss)); 

                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet; 

                    sheet.Name = "test"; 

                    int m = 0, n = 0; 

                    //生成Excel中列頭名稱    

                    for(int i = 0; i < dataGridView1.Columns.Count; i++) 

                    { 

                        excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;//輸出DataGridView列頭名 

                    } 

                    //把DataGridView當前頁的數據保存在Excel中    

                    for(int i = 0; i < dataGridView1.Rows.Count - 1; i++) 

                    { 

                        for(int j = 0; j < dataGridView1.Columns.Count; j++) 

                        { 

                            if(dataGridView1[j, i].ValueType == typeof(string)) 

                            { 

                                excel.Cells[i + 2, j + 1] = "'" + dataGridView1[j, i].Value.ToString(); 

                            } 

                            else 

                            { 

                                excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString(); 

                            } 

                        } 

                    } 

                    sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss); 

                    book.Close(false, miss, miss); 

                    books.Close(); 

                    excel.Quit(); 

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); 

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(book); 

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(books); 

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 

                    GC.Collect(); 

                    MessageBox.Show("數據已經成功導出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 

                    // toolStripProgressBar1.Value = 0; 

                    System.Diagnostics.Process.Start(strName); 

                } 

            } 

            catch(Exception ex) 

            { 

                MessageBox.Show(ex.Message, "錯誤提示"); 

            } 

        } 

 

        public void printAll(System.Data.DataTable dt) 

        { 

            //導出到execl 

            try 

            { 

                 SaveFileDialog saveFileDialog = new SaveFileDialog(); 

                saveFileDialog.Filter = "導出Excel (*.xls)|*.xls"; 

                saveFileDialog.FilterIndex = 0; 

                saveFileDialog.RestoreDirectory = true; 

                saveFileDialog.CreatePrompt = true; 

                saveFileDialog.Title = "導出文件保存路徑"; 

                saveFileDialog.ShowDialog(); 

                string strName = saveFileDialog.FileName; 

                if(strName.Length != 0) 

                { 

                    //沒有數據的話就不往下執行 

                    if(dt.Rows.Count == 0) 

                        return; 

 

                    // toolStripProgressBar1.Visible = true; 

                    System.Reflection.Missing miss = System.Reflection.Missing.Value; 

                    //實例化一個Excel.Application對象 

                    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 

                    excel.Application.Workbooks.Add(true); 

                    excel.Visible = false;//若是true,則在導出的時候會顯示EXcel界面。 

                    if(excel == null) 

                    { 

                        MessageBox.Show("EXCEL無法啟動!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); 

                        return; 

                    } 

                    Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks; 

                    Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss)); 

                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet; 

                    sheet.Name = "test"; 

                    int m = 0, n = 0; 

 

 

                    //生成Excel中列頭名稱 

                    for(int i = 0; i < dt.Columns.Count; i++) 

                    { 

                        excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;//輸出DataGridView列頭名 

                    } 

 

                    //把DataGridView當前頁的數據保存在Excel中 

                    if(dt.Rows.Count > 0) 

                    { 

                        for(int i = 0; i < dt.Rows.Count; i++)//控制Excel中行,上下的距離,就是可以到Excel最下的行數,比數據長了報錯,比數據短了會顯示不完 

                        { 

                            for(int j = 0; j < dt.Columns.Count; j++)//控制Excel中列,左右的距離,就是可以到Excel最右的列數,比數據長了報錯,比數據短了會顯示不完 

                            { 

                                string str = dt.Rows[i][j].ToString(); 

                                excel.Cells[i + 2, j + 1] = "'" + str;//i控制行,從Excel中第2行開始輸出第一行數據,j控制列,從Excel中第1列輸出第1列數據,"'" +是以string形式保存,所以遇到數字不會轉成16進制 

                            } 

                        } 

                    } 

                    sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss); 

                    book.Close(false, miss, miss); 

                    books.Close(); 

                    excel.Quit(); 

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); 

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(book); 

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(books); 

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 

 

                    GC.Collect(); 

                    MessageBox.Show("數據已經成功導出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 

                    // toolStripProgressBar1.Value = 0; 

                    System.Diagnostics.Process.Start(strName); 

                } 

            } 

            catch(Exception ex) 

            { 

                MessageBox.Show(ex.Message, "錯誤提示"); 

            } 

        } 

 

        private void SqlDB_To_Excel_Load(object sender, EventArgs e) 

        { 

            dataGridView1.DataSource = GetDataTableFromSqlServer(); 

        } 

 

        private void button2_Click(object sender, EventArgs e) 

        { 

            printAll(GetDataTableFromSqlServer()); 

        } 

 

        private System.Data.DataTable GetDataTableFromSqlServer() 

        { 

            string sqlconn = "database=database1;server=localhost;uid=sa;pwd=sa"; 

            SqlConnection cn = new SqlConnection(sqlconn); 

            string cmdText = "select * from users"; 

            SqlDataAdapter da = new SqlDataAdapter(cmdText, cn); 

            DataSet ds = new DataSet(); 

            da.Fill(ds, "table1"); 

            return ds.Tables[0]; 

        } 

 

        private System.Data.DataTable GetDataTableFromOracle() 

        { 

            string oracleconn = "Data Source=192.168.2.105/Database1;User ID=system;Password=ss;Unicode=True"; 

            OracleConnection cn = new OracleConnection(oracleconn); 

            string cmdText = "select * from users"; 

            OracleDataAdapter da = new OracleDataAdapter(cmdText, cn); 

            DataSet ds = new DataSet(); 

            da.Fill(ds, "table1"); 

            return ds.Tables[0]; 

        } 

    } 

 

 

結果:

\

 

代碼的思想就是將數據從數據庫中讀出到DataTable或者DataGridView中,然後遍歷他們的每一個單元格的值,給Excel對應的單元格賦值。

 

使用DataTable作為遍歷的對象,是為了去除分頁的困擾。

 

看到這裡,如果換一個List<T>對象集合,也應該能導出到數據庫中了。

 

2,Excel數據導入到數據庫

 

 

 

在WinForm中Excel導入到數據庫中和在WebForm中的導入過程是一樣的。可參見前面的內容。

 

這個系列的博客到此結束!



摘自 cpcpc的專欄

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved