天天看點

C#資料庫資料導入導出系列之四 WinForm資料庫導入導出到Excel

C#資料庫資料導入導出系列之四 WinForm資料庫導入導出到Excel

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

這裡将分為Asp.net導入Sql Server,Oracle資料庫和WinForm導入Sql Server,Oracle資料庫。

C#資料庫資料導入導出系列之一 ASP.NET Excel導入Sql Server資料庫

C#資料庫資料導入導出系列之二 資料庫導出到Excel上

C#資料庫資料導入導出系列之三 資料庫導出到Excel下

C#資料庫資料導入導出系列之四 WinForm資料庫導入導出到Excel

(注意 這裡四篇文章隻是基礎的方法,若有更高的要求,可以參考

http://www.cnblogs.com/atao/archive/2009/11/15/1603528.html

http://www.cnblogs.com/tonyqus/category/182110.html 

http://www.yongfa365.com/Item/NPOI-MyXls-DataTable-To-Excel-From-Excel.html .net 通過NPOI或MyXls把DataTable導出到Excel

這裡将的資料庫資料庫導入導出,其實對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

先看界面

C#資料庫資料導入導出系列之四 WinForm資料庫導入導出到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];
        }
    }
}
           

結果:

C#資料庫資料導入導出系列之四 WinForm資料庫導入導出到Excel

代碼的思想就是将資料從資料庫中讀出到DataTable或者DataGridView中,然後周遊他們的每一個單元格的值,給Excel對應的單元格指派。

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

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

2,Excel資料導入到資料庫

在WinForm中Excel導入到資料庫中和在WebForm中的導入過程是一樣的。可參見前面的内容。

這個系列的部落格到此結束!