在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#数据库操作 → C# Txt Excel Access导入导出功能

C# Txt Excel Access导入导出功能

C#数据库操作

下载此实例
  • 开发语言:C#
  • 实例大小:0.03M
  • 下载次数:301
  • 浏览次数:1963
  • 发布时间:2016-03-19
  • 实例类别:C#数据库操作
  • 发 布 人:jim197911
  • 文件格式:.rar
  • 所需积分:2
 相关标签:

实例介绍

【实例简介】C#所有导入导出功能,包括TXT导入,TXT导入出,EXCEL导入,EXCEK导出。-C# All import and export functions, including TXT import, TXT import out, EXCEL Import, EXCEK export.
【实例截图】

【核心代码】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;



namespace ExpImpProj
{
    public partial class Form1 : Form
    {

        private SMOHelper smoHelper = null;

        public Form1()
        {
            InitializeComponent();
        }

        public static void ImportAccessToDataGridView(DataGridView dataGridview1)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Microsoft Access 文件(*.mdb)|*.mdb";
            openFileDialog.Title = "选择Access文件";

            if (DialogResult.Cancel == openFileDialog.ShowDialog())
            {
                return;
            }

            string AccessPath = openFileDialog.FileName;


            string ConnectionAccess = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" AccessPath ";";

            OleDbConnection conn = new OleDbConnection(ConnectionAccess);
            conn.Open();

            string tablename = "";
            DataTable dt = conn.GetSchema("Tables");//获取ACCESS数据库中所有的表\查询\宏\窗体\模块
            for (int i = 0; i < dt.Rows.Count; i )
            {
                if (dt.Rows[i].ItemArray[3].ToString() == "TABLE")//判断是否是用户表
                {
                    tablename = dt.Rows[i].ItemArray[2].ToString();

                }
            }

            dataGridview1.Rows.Clear();
            dataGridview1.Columns.Clear();

            OleDbDataAdapter adp = new OleDbDataAdapter("Select * from  " tablename, conn);
            DataSet ds = new DataSet();
            adp.Fill(ds, "Book1");

            dataGridview1.DataSource = ds.Tables[0].DefaultView;

            conn.Close();

            MessageBox.Show("导入完成");
        }

        public static void ExportDataGridViewToAccess(DataGridView dataGridview1)
        {

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Access files (*.mdb)|*.mdb";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Access文件到";

            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            string AccessPath = saveFileDialog.FileName;

            DeleteFile(AccessPath); //文件存在则删除;
            ADOX.CatalogClass cat = new ADOX.CatalogClass();
            cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" AccessPath ";");  //创建数据库文件
            MessageBox.Show("数据库:" AccessPath "已经创建成功!");

            OleDbParameter[] parm = new OleDbParameter[dataGridview1.ColumnCount];

            string ConnectionAccess = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" AccessPath ";";

            OleDbConnection conn = new OleDbConnection(ConnectionAccess);
            conn.Open();

            OleDbCommand objCmd = new OleDbCommand();
            objCmd.Connection = conn;
            //建立表结构   

            string CommTitleTxt = "";

            CommTitleTxt = "CREATE   TABLE   Table1(";

            //写标题  
            for (int i = 0; i < dataGridview1.ColumnCount; i )
            {
                if (i > 0)
                {
                    CommTitleTxt = " varchar,";
                }
                CommTitleTxt = dataGridview1.Columns[i].HeaderText;
            }

            CommTitleTxt = " varchar)";


            objCmd.CommandText = CommTitleTxt;
            objCmd.ExecuteNonQuery();
            //建立插入动作的Command   

            string CommContextstr = "";
            CommContextstr = "INSERT   INTO   Table1(";
            for (int j = 0; j < dataGridview1.ColumnCount; j )
            {
                if (j != 0)
                    CommContextstr = ",";
                CommContextstr = dataGridview1.Columns[j].HeaderText;
            }

            CommContextstr = ")";

            CommContextstr = " Values(";

            for (int j = 0; j < dataGridview1.ColumnCount; j )
            {
                if (j != 0)
                    CommContextstr = ",";
                CommContextstr = "@" dataGridview1.Columns[j].HeaderText;
            }

            CommContextstr = ")";

            objCmd.CommandText = CommContextstr;

            for (int k = 0; k < dataGridview1.ColumnCount; k )
            {
                parm[k] = new OleDbParameter("@" dataGridview1.Columns[k].HeaderText, OleDbType.VarChar);
                objCmd.Parameters.Add(parm[k]);
            }

            ////遍历DataGridView将数据插入新建的Access文件中   
            for (int j = 0; j < dataGridview1.Rows.Count - 1; j )
            {
                for (int k = 0; k < dataGridview1.Columns.Count; k )
                {
                    if (dataGridview1.Rows[j].Cells[k].Value != null)
                        parm[k].Value = dataGridview1.Rows[j].Cells[k].Value.ToString();
                }
                objCmd.ExecuteNonQuery();
                System.Windows.Forms.Application.DoEvents();
            }

            conn.Close();
            MessageBox.Show("完成导出");

            // Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\Documents and Settings\Administrator\桌面\db1.mdb"


        }


        public static void ExportDataGridViewToWord(DataGridView dataGridview1)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "WORD files (*.DOC)|*.DOC";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出WORD文件到";

            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string str = "";
            try
            {
                //写标题  
                for (int i = 0; i < dataGridview1.ColumnCount; i )
                {
                    if (i > 0)
                    {
                        str = "\t";
                    }
                    str = dataGridview1.Columns[i].HeaderText;
                }

                sw.WriteLine(str);
                //写内容 
                for (int j = 0; j < dataGridview1.Rows.Count; j )
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGridview1.Columns.Count; k )
                    {
                        if (k > 0)
                        {
                            tempStr = "\t";
                        }
                        if (dataGridview1.Rows[j].Cells[k].Value != null)
                            tempStr = dataGridview1.Rows[j].Cells[k].Value.ToString();
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
                MessageBox.Show("完成导出");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }


        }

        public static void ImportExcelToDataGridView(DataGridView dataGridview1)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Microsoft Excel 文件(*.xls)|*.xls";
            openFileDialog.Title = "选择Excel文件";

            if (DialogResult.Cancel == openFileDialog.ShowDialog())
            {
                return;
            }

            string ExcelPath = openFileDialog.FileName;
            //  txtExcelPath.Text = ExcelPath;

            string ConnectionExcel = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" ExcelPath ";" "Extended Properties=Excel 8.0;";

            OleDbConnection conn = new OleDbConnection(ConnectionExcel);
            conn.Open();
            System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);

            dataGridview1.Rows.Clear();
            dataGridview1.Columns.Clear();

            string tableName = schemaTable.Rows[0][2].ToString().Trim(new char[] { '$', '\'' });

            OleDbDataAdapter adp = new OleDbDataAdapter("Select * from  [" tableName "$]", conn);
            DataSet ds = new DataSet();
            adp.Fill(ds, "Book1");

            dataGridview1.DataSource = ds.Tables[0].DefaultView;

            conn.Close();

            MessageBox.Show("导入完成");

        }


        public static void ExportDataGridViewToTXT(DataGridView dataGridview1)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "TXT files (*.txt)|*.txt";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出TXT文件到";

            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string str = "";
            try
            {
                //写标题  
                for (int i = 0; i < dataGridview1.ColumnCount; i )
                {
                    if (i > 0)
                    {
                        str = "\t";
                    }
                    str = dataGridview1.Columns[i].HeaderText;
                }

                sw.WriteLine(str);
                //写内容 
                for (int j = 0; j < dataGridview1.Rows.Count; j )
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGridview1.Columns.Count; k )
                    {
                        if (k > 0)
                        {
                            tempStr = "\t";
                        }
                        if (dataGridview1.Rows[j].Cells[k].Value != null)
                            tempStr = dataGridview1.Rows[j].Cells[k].Value.ToString();
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
                MessageBox.Show("完成导出");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }

        public static void ExportDataGridViewToExcel2(DataGridView dataGridview1)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Excel文件到";
            if (saveFileDialog.ShowDialog() != DialogResult.OK)
                return;

            string FileName = saveFileDialog.FileName;

            DeleteFile(FileName); //文件已存在,则删除;
            OleDbParameter[] parm = new OleDbParameter[dataGridview1.ColumnCount];

            string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" FileName ";" "Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(connString);
            conn.Open();

            OleDbCommand objCmd = new OleDbCommand();
            objCmd.Connection = conn;
            //建立表结构   

            string CommTitleTxt = "";

            CommTitleTxt = "CREATE   TABLE   Sheet1(";

            //写标题  
            for (int i = 0; i < dataGridview1.ColumnCount; i )
            {
                if (i > 0)
                {
                    CommTitleTxt = " varchar,";
                }
                CommTitleTxt = dataGridview1.Columns[i].HeaderText;
            }

            CommTitleTxt = " varchar)";


            objCmd.CommandText = CommTitleTxt;
            objCmd.ExecuteNonQuery();
            //建立插入动作的Command   

            string CommContextstr = "";
            CommContextstr = "INSERT   INTO   Sheet1(";
            for (int j = 0; j < dataGridview1.ColumnCount; j )
            {
                if (j != 0)
                    CommContextstr = ",";
                CommContextstr = dataGridview1.Columns[j].HeaderText;
            }

            CommContextstr = ")";

            CommContextstr = " Values(";

            for (int j = 0; j < dataGridview1.ColumnCount; j )
            {
                if (j != 0)
                    CommContextstr = ",";
                CommContextstr = "@" dataGridview1.Columns[j].HeaderText;
            }

            CommContextstr = ")";

            objCmd.CommandText = CommContextstr;

            for (int k = 0; k < dataGridview1.ColumnCount; k )
            {
                parm[k] = new OleDbParameter("@" dataGridview1.Columns[k].HeaderText, OleDbType.VarChar);
                objCmd.Parameters.Add(parm[k]);
            }

            ////遍历DataGridView将数据插入新建的Excel文件中   
            for (int j = 0; j < dataGridview1.Rows.Count - 1; j )
            {
                for (int k = 0; k < dataGridview1.Columns.Count; k )
                {
                    if (dataGridview1.Rows[j].Cells[k].Value != null)
                        parm[k].Value = dataGridview1.Rows[j].Cells[k].Value.ToString();
                }
                objCmd.ExecuteNonQuery();
                System.Windows.Forms.Application.DoEvents();
            }

            conn.Close();
            MessageBox.Show("完成导出");

        }


        public static void ExportDataGridViewToExcel(DataGridView dataGridview1)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Excel文件到";

            saveFileDialog.ShowDialog();

            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string str = "";
            try
            {
                //写标题  
                for (int i = 0; i < dataGridview1.ColumnCount; i )
                {
                    if (i > 0)
                    {
                        str = "\t";
                    }
                    str = dataGridview1.Columns[i].HeaderText;
                }

                sw.WriteLine(str);
                //写内容 
                for (int j = 0; j < dataGridview1.Rows.Count; j )
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGridview1.Columns.Count; k )
                    {
                        if (k > 0)
                        {
                            tempStr = "\t";
                        }
                        if (dataGridview1.Rows[j].Cells[k].Value != null)
                            tempStr = dataGridview1.Rows[j].Cells[k].Value.ToString();
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
                MessageBox.Show("完成导出");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }

        public static void ImportTxtToView(DataGridView DataGridview1)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "文本文件(*.txt)|*.txt";
            openFileDialog.Title = "选择文本文件";

            if (DialogResult.Cancel == openFileDialog.ShowDialog())
            {
                return;
            }

            string filename = openFileDialog.FileName;
            //打开文件并显示其内容 
            StreamReader reader = null;
            try
            {
                reader = new StreamReader(filename);

                DataTable dt = new DataTable();
                DataRow row;

                int linenum = 0;
                for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
                {
                    if (linenum == 0)
                        dt = MakeNamesTable(line);   //首行为标题;
                    else
                    {
                        row = dt.NewRow();
                        int i = 0;
                        string[] tmpstrs = line.Split('\t');
                        foreach (string tmpstr in tmpstrs)
                        {
                            row[i] = tmpstr;
                            i ;
                        }
                        dt.Rows.Add(row);
                    }
                    linenum ;
                }
                DataGridview1.DataSource = dt;
            }
            catch (IOException e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }

        }

        public static DataTable MakeNamesTable(string linestr)
        {
            // Create a new DataTable titled 'Names.'
            DataTable namesTable = new DataTable("Names");

            string[] tmpstrs = linestr.Split('\t');

            DataColumn[] idColumn = new DataColumn[tmpstrs.Length];
            int i = 0;
            foreach (string tmpstr in tmpstrs)
            {
                idColumn[i] = new DataColumn();
                idColumn[i].DataType = System.Type.GetType("System.String");
                idColumn[i].ColumnName = tmpstr;
                namesTable.Columns.Add(idColumn[i]);
                i ;
            }

            // Return the new DataTable.
            return namesTable;
        }

        public static DataSet SqlQuery(string SqlStr, string connstr)
        {

            // Connectionstring "Data Source=JUNCHENG-AAE091;Initial Catalog=model;Integrated Security=True";
            DataSet ds = new DataSet();
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = connstr;
            try
            {

                conn.Open();
                SqlDataAdapter adap = new SqlDataAdapter(SqlStr, conn);
                adap.Fill(ds, "Import");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
            return ds;
        }


        public static void ExportSqlToTxt(string Sqlstr, string connstr)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "TXT files (*.txt)|*.txt";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出TXT文件到";

            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }


            DataSet ds = SqlQuery(Sqlstr, connstr);  //获取SQL语句的结果集

            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string str = "";
            try
            {
                //写标题  
                for (int i = 0; i < ds.Tables[0].Columns.Count; i )
                {
                    if (i > 0)
                    {
                        str = "\t";
                    }
                    str = ds.Tables[0].Columns[i].ColumnName;
                }

                sw.WriteLine(str);
                //写内容 
                for (int j = 0; j < ds.Tables[0].Rows.Count; j )
                {
                    string tempStr = "";
                    for (int k = 0; k < ds.Tables[0].Columns.Count; k )
                    {
                        if (k > 0)
                        {
                            tempStr = "\t";
                        }
                        if (ds.Tables[0].Rows[j][k] != null)
                            tempStr = ds.Tables[0].Rows[j][k].ToString();
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
                MessageBox.Show("完成导出");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }

        public static void ExportSqlToExcel(string SqlStr, string connstr)
        {

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Excel文件到";
            if (saveFileDialog.ShowDialog() != DialogResult.OK)
                return;

            DataSet ds = SqlQuery(SqlStr, connstr);

            string FileName = saveFileDialog.FileName;

            DeleteFile(FileName); //文件已存在,则删除;

            OleDbParameter[] parm = new OleDbParameter[ds.Tables[0].Columns.Count];

            string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" FileName ";" "Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(connString);
            conn.Open();

            OleDbCommand objCmd = new OleDbCommand();
            objCmd.Connection = conn;
            //建立表结构   

            string CommTitleTxt = "";

            CommTitleTxt = "CREATE   TABLE   Sheet1(";

            //写标题  
            for (int i = 0; i < ds.Tables[0].Columns.Count; i )
            {
                if (i > 0)
                {
                    CommTitleTxt = " varchar,";
                }
                CommTitleTxt = ds.Tables[0].Columns[i].ColumnName;
            }

            CommTitleTxt = " varchar)";


            objCmd.CommandText = CommTitleTxt;
            objCmd.ExecuteNonQuery();
            //建立插入动作的Command   

            string CommContextstr = "";
            CommContextstr = "INSERT   INTO   Sheet1(";
            for (int j = 0; j < ds.Tables[0].Columns.Count; j )
            {
                if (j != 0)
                    CommContextstr = ",";
                CommContextstr = ds.Tables[0].Columns[j].ColumnName;
            }

            CommContextstr = ")";

            CommContextstr = " Values(";

            for (int j = 0; j < ds.Tables[0].Columns.Count; j )
            {
                if (j != 0)
                    CommContextstr = ",";
                CommContextstr = "@" ds.Tables[0].Columns[j].ColumnName;
            }

            CommContextstr = ")";

            objCmd.CommandText = CommContextstr;

            for (int k = 0; k < ds.Tables[0].Columns.Count; k )
            {
                parm[k] = new OleDbParameter("@" ds.Tables[0].Columns[k].ColumnName, OleDbType.VarChar);
                objCmd.Parameters.Add(parm[k]);
            }

            ////遍历数据集DS将数据插入新建的Excel文件中   
            for (int j = 0; j < ds.Tables[0].Rows.Count - 1; j )
            {
                for (int k = 0; k < ds.Tables[0].Columns.Count; k )
                {
                    if (ds.Tables[0].Rows[j][k] != null)
                        parm[k].Value = ds.Tables[0].Rows[j][k].ToString();
                }
                objCmd.ExecuteNonQuery();
                System.Windows.Forms.Application.DoEvents();
            }

            conn.Close();
            MessageBox.Show("完成导出");
        }

        public static void DeleteFile(string strPath)
        {
            if (File.Exists(strPath))
            {
                File.Delete(strPath);
            }
        }

        public static void ExportSqlToAccess(string SqlStr, string connstr)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Access files (*.mdb)|*.mdb";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Access文件到";

            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            DataSet ds = SqlQuery(SqlStr, connstr);



            string AccessPath = saveFileDialog.FileName;
            DeleteFile(AccessPath); //文件已存在,则删除;


            ADOX.CatalogClass cat = new ADOX.CatalogClass();
            cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" AccessPath ";");  //创建数据库文件
            MessageBox.Show("数据库:" AccessPath "已经创建成功!");

            OleDbParameter[] parm = new OleDbParameter[ds.Tables[0].Columns.Count];

            string ConnectionAccess = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" AccessPath ";";

            OleDbConnection conn = new OleDbConnection(ConnectionAccess);
            conn.Open();

            OleDbCommand objCmd = new OleDbCommand();
            objCmd.Connection = conn;
            //建立表结构   

            string CommTitleTxt = "";



            CommTitleTxt = "CREATE   TABLE   Table1(";

            //写标题  
            for (int i = 0; i < ds.Tables[0].Columns.Count; i )
            {
                if (i > 0)
                {
                    CommTitleTxt = " varchar,";
                }
                CommTitleTxt = ds.Tables[0].Columns[i].ColumnName;
            }

            CommTitleTxt = " varchar)";


            objCmd.CommandText = CommTitleTxt;
            objCmd.ExecuteNonQuery();
            //建立插入动作的Command   

            string CommContextstr = "";
            CommContextstr = "INSERT   INTO   Table1(";
            for (int j = 0; j < ds.Tables[0].Columns.Count; j )
            {
                if (j != 0)
                    CommContextstr = ",";
                CommContextstr = ds.Tables[0].Columns[j].ColumnName;
            }

            CommContextstr = ")";

            CommContextstr = " Values(";

            for (int j = 0; j < ds.Tables[0].Columns.Count; j )
            {
                if (j != 0)
                    CommContextstr = ",";
                CommContextstr = "@" ds.Tables[0].Columns[j].ColumnName;
            }

            CommContextstr = ")";

            objCmd.CommandText = CommContextstr;

            for (int k = 0; k < ds.Tables[0].Columns.Count; k )
            {
                parm[k] = new OleDbParameter("@" ds.Tables[0].Columns[k].ColumnName, OleDbType.VarChar);
                objCmd.Parameters.Add(parm[k]);
            }

            ////遍历DataGridView将数据插入新建的Access文件中   
            for (int j = 0; j < ds.Tables[0].Rows.Count - 1; j )
            {
                for (int k = 0; k < ds.Tables[0].Columns.Count; k )
                {
                    if (ds.Tables[0].Rows[j][k] != null)
                        parm[k].Value = ds.Tables[0].Rows[j][k].ToString();
                }
                objCmd.ExecuteNonQuery();
                System.Windows.Forms.Application.DoEvents();
            }

            conn.Close();
            MessageBox.Show("完成导出");

        }

        public static void MakeDbTable(SqlConnection conn, string tablename, string linestr)  //在数据库中建表;
        {

            // Connectionstring "Data Source=JUNCHENG-AAE091;Initial Catalog=model;Integrated Security=True";
            try
            {
                string commtxt = "CREATE TABLE " tablename "(";

                string[] tmpstrs = linestr.Split('\t');
                int i = 0;
                foreach (string tmpstr in tmpstrs)
                {
                    if (i != 0)
                        commtxt = ",";
                    commtxt = tmpstr;
                    commtxt = " varchar(50)";
                    i ;
                }

                commtxt = " )";

                SqlCommand comm = new SqlCommand(commtxt, conn);

                comm.ExecuteNonQuery();
                conn.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }
        }

        public static void InsertToTable(SqlConnection conn, string tablename, string linestr, string Titlestr)  //在表中插数据;
        {

            string[] tmpstrs2 = linestr.Split('\t');

            if (tmpstrs2.Length == 0)  //空数据直接返回;
                return;

            string commtxt = "Insert into " tablename "(";

            string[] tmpstrs = Titlestr.Split('\t');
            int i = 0;
            foreach (string tmpstr in tmpstrs)
            {
                if (i != 0)
                    commtxt = ",";
                commtxt = tmpstr;
                i ;
            }

            commtxt = ") Values(";


            int j = 0;
            foreach (string tmpstr2 in tmpstrs2)
            {
                if (j != 0)
                    commtxt = ",";
                commtxt = tmpstr2;
                j ;
            }

            commtxt = ")";

            SqlCommand comm = new SqlCommand(commtxt, conn);
            comm.ExecuteNonQuery();
            conn.Close();

        }


        public static void ImportTxtToDB(string SqlStr, string connstr, string tablename)
        {

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "文本文件(*.txt)|*.txt";
            openFileDialog.Title = "选择文本文件";

            if (DialogResult.Cancel == openFileDialog.ShowDialog())
            {
                return;
            }

            string filename = openFileDialog.FileName;
            SqlConnection conn = new SqlConnection(connstr);
            conn.Open();
            //打开文件并显示其内容 
            StreamReader reader = null;
            try
            {
                reader = new StreamReader(filename);

                string Titlestr = "";

                int linenum = 0;
                for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
                {
                    if (linenum == 0)
                    {
                        Titlestr = line;
                        if (!TableIsExists(conn, tablename))
                            MakeDbTable(conn, tablename, line);   //创建表;
                    }
                    else
                    {
                        InsertToTable(conn, tablename, line, Titlestr);   //表数据插入;
                    }
                    linenum ;
                }
                MessageBox.Show("导入完成");
            }
            catch (IOException e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                conn.Close();
            }
        }

        public void ImportExcelToDB(string connstr, string tablename)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Microsoft Excel 文件(*.xls)|*.xls";
            openFileDialog.Title = "选择Excel文件";

            if (DialogResult.Cancel == openFileDialog.ShowDialog())
            {
                return;
            }

            string ExcelPath = openFileDialog.FileName;
            //  txtExcelPath.Text = ExcelPath;

            string ConnectionExcel = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" ExcelPath ";" "Extended Properties=Excel 8.0;";

            OleDbConnection conn = new OleDbConnection(ConnectionExcel);
            conn.Open();
            System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);


            string EtableName = schemaTable.Rows[0][2].ToString().Trim(new char[] { '$', '\'' });

            OleDbDataAdapter adp = new OleDbDataAdapter("Select * from  [" EtableName "$]", conn);
            DataSet ds = new DataSet();
            adp.Fill(ds, "Book1");

            if (InsertSQLServer(ds, tablename, connstr))
            {
                MessageBox.Show("导入表数据完成");
            }
            else MessageBox.Show("导入表数据失败");
        }

        public void ImportAccessToDB(string connstr, string tablename)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Microsoft Access 文件(*.mdb)|*.mdb";
            openFileDialog.Title = "选择Access文件";

            if (DialogResult.Cancel == openFileDialog.ShowDialog())
            {
                return;
            }

            string AccessPath = openFileDialog.FileName;


            string ConnectionAccess = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" AccessPath ";";
            try
            {
                OleDbConnection conn = new OleDbConnection(ConnectionAccess);
                conn.Open();

                string Atablename = "";
                DataTable dt = conn.GetSchema("Tables");//获取ACCESS数据库中所有的表\查询\宏\窗体\模块
                for (int i = 0; i < dt.Rows.Count; i )
                {
                    if (dt.Rows[i].ItemArray[3].ToString() == "TABLE")//判断是否是用户表
                    {
                        Atablename = dt.Rows[i].ItemArray[2].ToString();

                    }
                }

                OleDbDataAdapter adp = new OleDbDataAdapter("Select * from  " Atablename, conn);
                DataSet ds = new DataSet();
                adp.Fill(ds, "Book1");

                if (InsertSQLServer(ds, tablename, connstr))
                    MessageBox.Show("导入表数据完成");
                else MessageBox.Show("导入表数据失败");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public static bool TableIsExists(SqlConnection conn, string tablename)  //表是否已经存在;
        {
            try
            {
                string SqlStr = "SELECT name FROM sysobjects WHERE type='U'and name ='" tablename "'";
                SqlCommand comm = new SqlCommand(SqlStr, conn);
                int iResult = 0;
                iResult = comm.ExecuteNonQuery();
                if (iResult == 0)
                    return false;
                else return true;
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
                return true;
            }
        }

        public static bool InsertSQLServer(DataSet ds, string tablename, string connstr)
        {
            try
            {
                SqlConnection con = new SqlConnection(connstr);//创建连接
                con.Open();

                string Titlestr = "";
                for (int i = 0; i < ds.Tables[0].Columns.Count; i ) //取字段名;
                {
                    if (i != 0)
                        Titlestr = "\t";  //tab字符分隔;
                    Titlestr = ds.Tables[0].Columns[i].ColumnName;
                }

                if (!TableIsExists(con, tablename))   //表不存在创建表;
                {
                    MakeDbTable(con, tablename, Titlestr);
                }

                for (int i = 0; i < ds.Tables[0].Rows.Count; i )
                {
                    string linestr = "";
                    for (int j = 0; j < ds.Tables[0].Columns.Count; j )
                    {
                        if (j != 0)
                            linestr = "\t";    //Tab字符分隔;
                        if (ds.Tables[0].Rows[i][j] != null)
                            linestr = ds.Tables[0].Rows[i][j].ToString();
                        else linestr = " ";
                    }
                    InsertToTable(con, tablename, linestr, Titlestr);//插入数据
                }
                con.Close();
                return true;
            }
            catch
            {
                return false;
            }

        }

        public static bool btnExecuteSql(string SqlStr, string connstr, DataGridView dgv)
        {
            try
            {
                DataSet ds = SqlQuery(SqlStr, connstr);
                if (ds.Tables.Count != 0)
                    dgv.DataSource = ds.Tables[0].DefaultView;
                else dgv.DataSource = null;
                return true;
            }
            catch
            {
                return false;
                //不显示错误信息
            }
        }


        /*    public  void DBBackup(string ServerName, string UserName, string Pwd, string DBName)
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.FileName = "Backup" DateTime.Now.ToString("yyyyMMddhhmmss") ".bak";
                saveFileDialog.Filter = "Backup files (*.bak)|*.bak";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.InitialDirectory = @"C:\";
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.CreatePrompt = true;
                saveFileDialog.Title = "备份文件到";

                if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }

            


                /* SQLDMO.Backup backup = new SQLDMO.BackupClass();

                try
                {

                
                    backup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                    backup.Database = DBName;
                
                    backup.Files = 
                    backup.BackupSetName = "DBName";
                    backup.BackupSetDescription = "数据库备份";
                    backup.Initialize = true;
                    backup.PercentCompleteNotification = 10;
                    backup.PercentComplete = new PercentCompleteEventHandler(backup_PercentComplete);
                    backup.Complete = new ServerMessageEventHandler(backup_Complete);
                    backup.SQLBackup(sqlserver);
                
                }
                catch (Exception ex)
                {
                    throw (new Exception("备份数据库失败" ex));

                }
                finally
                {
                   sqlserver.DisConnect();
                } 
            }*/

        /*   public static void ReconveDB(string ServerName, string UserName, string Pwd, string DBName)
           {
               OpenFileDialog openFileDialog = new OpenFileDialog();
               openFileDialog.Filter = "Backup files (*.bak)|*.bak";
               openFileDialog.Title = "选择备份文件";

               if (DialogResult.Cancel == openFileDialog.ShowDialog())
               {
                   return;
               }

               SQLDMO.Restore restore = new SQLDMO.RestoreClass();
               SQLDMO.SQLServer sqlserver = new SQLDMO.SQLServerClass();
               try
               {
                   sqlserver.LoginSecure = false;
                   sqlserver.Connect(ServerName, UserName, Pwd);
                   restore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
                   restore.Database = DBName;
                   restore.Files = openFileDialog.FileName;
                   restore.FileNumber = 1;
                   restore.ReplaceDatabase = true;
                   restore.SQLRestore(sqlserver);
               }
               catch (Exception ex)
               {
                   throw (new Exception("还原数据库失败" ex));
               }
               finally
               {
                   sqlserver.DisConnect();
               }

           } */

        private void btnExpExcel_Click(object sender, EventArgs e)
        {
            ExportDataGridViewToExcel(dgv);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ExportDataGridViewToWord(dgv);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ImportExcelToDataGridView(dgv1);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ExportDataGridViewToTXT(dgv);
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            ImportTxtToView(dgv1);
        }

        private void button3_Click_2(object sender, EventArgs e)
        {
            ExportDataGridViewToExcel2(dgv);
        }

        private void ViewToAccess_Click(object sender, EventArgs e)
        {
            ExportDataGridViewToAccess(dgv);
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            ImportAccessToDataGridView(dgv1);
        }

        private void SqlToTxt_Click(object sender, EventArgs e)
        {
            ExportSqlToTxt(rtbSql.Text.Trim(), tbConnStr.Text);
        }

        private void SqlToExcel_Click(object sender, EventArgs e)
        {
            ExportSqlToExcel(rtbSql.Text.Trim(), tbConnStr.Text);
        }

        private void SqlToAccess_Click(object sender, EventArgs e)
        {
            ExportSqlToAccess(rtbSql.Text.Trim(), tbConnStr.Text);
        }

        private void TxtToDB_Click(object sender, EventArgs e)
        {
            ImportTxtToDB(rtbSql.Text.Trim(), tbConnStr.Text, "TestTab");
        }

        private void ExcelToDB_Click(object sender, EventArgs e)
        {
            ImportExcelToDB(tbConnStr.Text, "TestTab");
        }



        private void Execute_Click(object sender, EventArgs e)
        {
            if (btnExecuteSql(rtbSql.Text.Trim(), tbConnStr.Text, dgvSQLResult))
                lbResult.Text = "ExcuteResult:OK";
            else lbResult.Text = "ExcuteResult:Fail";
        }

        private void AccessToDB_Click(object sender, EventArgs e)
        {
            ImportAccessToDB(tbConnStr.Text, "TestTab");
        }

        private void TabBackup_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = "Backup" DateTime.Now.ToString("yyyyMMddhhmmss") ".bak";
            saveFileDialog.Filter = "Backup files (*.bak)|*.bak";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.InitialDirectory = @"C:\";
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "备份文件到";

            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            smoHelper = new SMOHelper("JUNCHENG-AAE091", "sa", "li", false);
            smoHelper.Connect();
            if (smoHelper.Server != null)
            {
                smoHelper.BackupPercentCompleteChanging = Backup_PercentCompleteChanging;
                smoHelper.BackupComplete = Backup_Complete;
                smoHelper.RestorePercentCompleteChanging = Restore_PercentCompleteChanging;
                smoHelper.RestoreComplete = Restore_Complete;
            }


            pbar.Maximum = 100;
            pbar.Style = ProgressBarStyle.Blocks;
            pbar.Value = 0;
            pbar.Step = 10;
            string databaseName = "model";
            smoHelper.BackupDatabase(databaseName, saveFileDialog.FileName);
            smoHelper.DisConnect();
        }

        public void Backup_Complete(object sender, ServerMessageEventArgs e)
        {
            pbar.Value = pbar.Maximum;
            string databaseName = ((Backup)sender).Database;
            string msg = string.Format("Database {0} has been backed up successfully!", databaseName);
            MessageBox.Show(msg);
            pbar.Value = 0;
        }
        public void Backup_PercentCompleteChanging(object sender, PercentCompleteEventArgs e)
        {
            pbar.PerformStep();
        }
        public void Restore_Complete(object sender, ServerMessageEventArgs e)
        {
            pbar.Value = pbar.Maximum;
            string databaseName = ((Restore)sender).Database;
            string msg = string.Format("Database {0} has been restored successfully!", databaseName);
            MessageBox.Show(msg);
            pbar.Value = 0;
        }
        public void Restore_PercentCompleteChanging(object sender, PercentCompleteEventArgs e)
        {
            pbar.PerformStep();
        }

        private void ReconverDB_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Backup files (*.bak)|*.bak";
            openFileDialog.Title = "选择备份文件";

            if (DialogResult.Cancel == openFileDialog.ShowDialog())
            {
                return;
            }

            smoHelper = new SMOHelper("JUNCHENG-AAE091", "sa", "li", false);
            smoHelper.Connect();
            if (smoHelper.Server != null)
            {
                smoHelper.BackupPercentCompleteChanging = Backup_PercentCompleteChanging;
                smoHelper.BackupComplete = Backup_Complete;
                smoHelper.RestorePercentCompleteChanging = Restore_PercentCompleteChanging;
                smoHelper.RestoreComplete = Restore_Complete;
            }

            pbar.Maximum = 100;
            pbar.Style = ProgressBarStyle.Blocks;
            pbar.Value = 0;
            pbar.Step = 10;
            string databaseName = "model";
            smoHelper.RestoreDB(databaseName, openFileDialog.FileName);
            smoHelper.DisConnect();
        }

        private void tbConnStr_TextChanged(object sender, EventArgs e)
        {

        }

        private void pbar_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

    }
}

标签:

实例下载地址

C# Txt Excel Access导入导出功能

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 拍死你喽 发表于: 2018-06-21 13:54 58
为啥下载不了啊

支持(0) 盖楼(回复)

第 2 楼 freefly 发表于: 2021-10-17 23:30 47
动态库没有打包全

支持(0) 盖楼(回复)

第 3 楼 freefly 发表于: 2021-10-17 23:30 51
动态库没有打包全

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有3条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警