C#将Excel数据导入现有MDB数据库

时间:2018-04-06 13:41:32

标签: excel import oledb access

我有一个Access MDB文件,只有一个表简称为“Sheet1”。 Inside Sheet1我已经识别了Fields,但是我把这些表留空了。

我正在尝试将CS​​V文件中的数据复制到Access Sheet1表中。

如果该表尚不存在,则下面的代码有效,但我在AccessCommand.ExecuteNonQuery();行显示错误

  

System.Data.OleDb.OleDbException:表'Sheet1'已存在。

如何修改此代码,以便将CSV数据导入到已标识字段的空表中?

using System.Data.OleDb;

string filename = "MyCSV.csv";

int result = 0;
string dirPath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\";


string uploaderMDB = dirPath + "MyMDB.mdb";

OleDbConnection AccessConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + uploaderMDB);

AccessConnection.Open();

OleDbCommand AccessCommand = new OleDbCommand("SELECT * INTO [Sheet1] FROM [Text;FMT=Delimited;DATABASE=" + dirPath + ";HDR=No].[" + filename + "]", AccessConnection);


AccessCommand.ExecuteNonQuery();
AccessConnection.Close();

2 个答案:

答案 0 :(得分:1)

以这种方式试试。

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.Data.OleDb;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            OleDbConnection conn;
            conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\your_path_here\Northwind.mdb");

            conn.Open();

            OleDbCommand cmd = conn.CreateCommand();

            cmd.CommandText = @"INSERT INTO MyExcelTable([Fname], [Lname],  [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
            cmd.ExecuteNonQuery();
            conn.Close();

        }

        public OleDbConnection myCon { get; set; }

        private void button2_Click(object sender, EventArgs e)
        {

            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";

            string fstName  = textBox1.Text.Trim();
            string lstName  = textBox2.Text.Trim();
            string adres = textBox3.Text.Trim();
            OleDbCommand cmd = new OleDbCommand(@"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (@FName, @LName, @Address)")
            {
                Connection = conn
            };

            conn.Open();

            if (conn.State == ConnectionState.Open)
            {
                // you should always use parameterized queries to avoid SQL Injection
                cmd.Parameters.Add("@FName", OleDbType.VarChar).Value = fstName;
                cmd.Parameters.Add("@LName", OleDbType.VarChar).Value = lstName;
                cmd.Parameters.Add("@Address", OleDbType.VarChar).Value = adres;

                try
                {
                    cmd.ExecuteNonQuery();
                    MessageBox.Show(@"Data Added");
                    conn.Close();
                }
                catch (OleDbException ex)
                {
                    MessageBox.Show(ex.Source + "\n" + ex.Message);
                    conn.Close();
                }
            }
            else
            {
                MessageBox.Show(@"Connection Failed");
            }
        }
        }
    }

答案 1 :(得分:0)

我找到了一个解决方案(它需要XLSX而不是......)。它使用了 Microsoft.Office.Interop.Access引用而不是OleDb。

string filename = "MyXLSX.xlsx";

string dirPath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\";

string uploaderMDB = dirPath + "MyMDB.mdb";
string fullPath = dirPath + filename;


Application _accessData = new ApplicationClass();
_accessData.Visible = false;
_accessData.OpenCurrentDatabase(uploaderMDB);
_accessData.DoCmd.OpenTable("SHEET1");
_accessData.DoCmd.TransferSpreadsheet(AcDataTransferType.acImport, AcSpreadSheetType.acSpreadsheetTypeExcel12, "Sheet1", fullPath, true, "MY_NAMED_RANGE");
_accessData.CloseCurrentDatabase();
_accessData.Visible = true;
_accessData.Quit(AcQuitOption.acQuitSaveAll);

System.Runtime.InteropServices.Marshal.ReleaseComObject(_accessData);
_accessData = null;