【问题标题】:C# Import Excel Data into Existing MDB DatabaseC# 将 Excel 数据导入现有 MDB 数据库
【发布时间】:2018-09-16 13:32:36
【问题描述】:

我有一个 Access MDB 文件,其中只有一个名为“Sheet1”的表。在 Sheet1 中,我已经确定了字段,但我让表中没有任何记录。

我正在尝试将数据从 CSV 文件复制到 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();

【问题讨论】:

    标签: excel ms-access import oledb


    【解决方案1】:

    我为任何感兴趣的人找到了一个解决方案(虽然它需要 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;
    

    【讨论】:

      【解决方案2】:

      试试这个方法。

      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");
                  }
              }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2014-01-31
        • 2011-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-09
        • 2020-02-27
        • 2013-05-02
        • 2018-04-17
        相关资源
        最近更新 更多