Convert Excel data to MDB file

所需组件:

microsoft ado ext. 2.8 for ddl and security 或者更新的组件。

添加:

using ADOX;
using System.Runtime.InteropServices;
using System.IO;

然后利用OleDbCommand组件,设置其2个链接,一个链接负责查找并打开excel数据源,另一个链接负责将数据源插入到MDB文件中。

操作页面:

Convert Excel data to MDB file

后台源码:

  private void button1_Click(object sender, EventArgs e)

        {

            var MDbPath = this.txtMDBPath.Text;



            if (File.Exists(MDbPath) == false)

            {

                ADOX.Catalog catalog = new ADOX.Catalog(); dynamic cn = null;



                try

                {

                    cn = catalog.Create(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", MDbPath));

                }

                finally

                {

                    if (cn != null)

                    {

                        Marshal.FinalReleaseComObject(cn);

                    }

                    Marshal.FinalReleaseComObject(catalog);

                }



                string excelPath = this.txtExcelPath.Text;

                string excelConnection = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\"", excelPath);



                using (System.Data.OleDb.OleDbConnection AccessConn = new System.Data.OleDb.OleDbConnection(excelConnection))

                {

                    AccessConn.Open();



                    string insertCommandText = string.Format("SELECT * INTO [MS Access;DATABASE={0}].[Sheet1] from [Sheet1$];", MDbPath);



                    using (System.Data.OleDb.OleDbCommand AccessCommand = new System.Data.OleDb.OleDbCommand(insertCommandText, AccessConn))

                    {

                        AccessCommand.ExecuteNonQuery();

                    }

                    AccessConn.Close();

                }

            }

            MessageBox.Show("数据写入成功。");

        }

注意:insertCommandText中数据源链接部分必须写:DATABASE=...,不能写Data Source=...,否则会出现“表已经存在”的异常。

你可能感兴趣的:(convert)