2012-07-16 81 views
1

使用C#我試圖創建一個控制檯應用程序,從特定的文件夾位置讀取CSV文件並將這些記錄導入MS Access表。一旦文件中的記錄成功導入,我將刪除.csv文件。複製CSV文件到MS Access表

到目前爲止,這是我:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Configuration; 
using System.Data; 
using System.Data.OleDb; 
using System.Globalization; 

namespace QuantumTester 
{ 
class Program 
{ 
    static void Main(string[] args) 
    {   
     CsvFileToDatatable(ConfigurationManager.AppSettings["CSVFile"], true); 
    } 

    public static DataTable CsvFileToDatatable(string path, bool IsFirstRowHeader)//here Path is root of file and IsFirstRowHeader is header is there or not 
    { 
     string header = "Yes"; //"No" if 1st row is not header cols 
     string sql = string.Empty; 
     DataTable dataTable = null; 
     string pathOnly = string.Empty; 
     string fileName = string.Empty; 

     try 
     { 

      pathOnly = Path.GetDirectoryName(ConfigurationManager.AppSettings["QuantumOutputFilesLocation"]); 
      fileName = Path.GetFileName(ConfigurationManager.AppSettings["CSVFilename"]); 

      sql = @"SELECT * FROM [" + fileName + "]"; 

      if (IsFirstRowHeader) 
      { 
       header = "Yes"; 
      } 

      using (OleDbConnection connection = new OleDbConnection(
        @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + 
        ";Extended Properties=\"Text;HDR=" + header + "\"")) 
      { 
       using (OleDbCommand command = new OleDbCommand(sql, connection)) 
       { 
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command)) 
        { 
         dataTable = new DataTable(); 
         dataTable.Locale = CultureInfo.CurrentCulture; 
         adapter.Fill(dataTable); 
        } 
       } 
      } 
     } 
     finally 
     { 

     } 
     return dataTable; 
    } 
} 
} 

可我只是繼續的保存數據表到我在Access數據庫中創建一個表?我會如何去做這件事?任何幫助都會很棒

回答

1

您可以再次運行一個查詢,以便從CSV文件創建新表的Access連接或追加到現有表。

創建一個表將類似於SQL:

SELECT * INTO NewAccess 
FROM [Text;FMT=Delimited;HDR=NO;DATABASE=Z:\Docs].[Table1.csv] 

要追加到表:

INSERT INTO NewAccess 
SELECT * FROM [Text;FMT=Delimited;HDR=NO;DATABASE=Z:\Docs].[Table1.csv] 
+0

您需要對連接執行sql http://msdn.microsoft.com/en-us/library/system.data.ol edb.oledbconnection.aspx或更好,請使用命令並執行該命令。 – Fionnuala 2012-07-17 11:40:39

+0

我現在有我的代碼從CSV文件中選擇數據,我可以遍歷每一行/列,但我不知道如何將實際插入/更新插入MS Access數據庫。你能幫助我嗎? @Remou – paulmcm 2012-07-17 12:00:07

+0

我已經發布的SQL上面,當針對連接運行將插入到Access表中的CSV或創建一個新的Access表。它不需要你從CSV中選擇數據,它只是一個步驟。 – Fionnuala 2012-07-17 12:14:17

2

終於得到了這方面的工作,這就是我 - 希望它可以幫助別人否則在將來:

public static DataTable CsvFileToDatatable(string path, bool IsFirstRowHeader)//here Path is root of file and IsFirstRowHeader is header is there or not 
    { 
     string header = "Yes"; //"No" if 1st row is not header cols 
     string query = string.Empty; 
     DataTable dataTable = null; 
     string filePath = string.Empty; 
     string fileName = string.Empty; 

     try 
     { 
      //csv file directory 
      filePath = Path.GetDirectoryName(ConfigurationManager.AppSettings["QuantumOutputFilesLocation"]); 
      //csv file name 
      fileName = Path.GetFileName(ConfigurationManager.AppSettings["CSVFilename"]); 

      query = @"SELECT * FROM [" + fileName + "]"; 

      if (IsFirstRowHeader) header = "Yes"; 

      using (OleDbConnection connection = new OleDbConnection((@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Text;HDR=" + header + "\"")))    
      { 
       using (OleDbCommand command = new OleDbCommand(query, connection)) 
       { 
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command)) 
        {              
         dataTable = new DataTable(); 
         adapter.Fill(dataTable); 

         //create connection to Access DB 
         OleDbConnection DBconn = new OleDbConnection(ConfigurationManager.ConnectionStrings["Seagoe_QuantumConnectionString"].ConnectionString); 
         OleDbCommand cmd = new OleDbCommand(); 
         //set cmd settings 
         cmd.Connection = DBconn; 
         cmd.CommandType = CommandType.Text; 
         //open DB connection 
         DBconn.Open(); 
         //read each row in the Datatable and insert that record into the DB 
         for (int i = 0; i < dataTable.Rows.Count; i++) 
         { 
          cmd.CommandText = "INSERT INTO tblQuantum (DateEntered, Series, SerialNumber, YearCode, ModelNumber, BatchNumber, DeviceType, RatedPower, EnergyStorageCapacity," + 
                     "MaxEnergyStorageCapacity, User_IF_FWRevNo, Charge_Controller_FWRevNo, RF_Module_FWRevNo, SSEGroupNumber, TariffSetting)" + 
              " VALUES ('" + dataTable.Rows[i].ItemArray.GetValue(0) + "','" + dataTable.Rows[i].ItemArray.GetValue(1) + "','" + dataTable.Rows[i].ItemArray.GetValue(2) + 
              "','" + dataTable.Rows[i].ItemArray.GetValue(3) + "','" + dataTable.Rows[i].ItemArray.GetValue(4) + "','" + dataTable.Rows[i].ItemArray.GetValue(5) + 
              "','" + dataTable.Rows[i].ItemArray.GetValue(6) + "','" + dataTable.Rows[i].ItemArray.GetValue(7) + "','" + dataTable.Rows[i].ItemArray.GetValue(8) + 
              "','" + dataTable.Rows[i].ItemArray.GetValue(9) + "','" + dataTable.Rows[i].ItemArray.GetValue(10) + "','" + dataTable.Rows[i].ItemArray.GetValue(11) + 
              "','" + dataTable.Rows[i].ItemArray.GetValue(12) + "','" + dataTable.Rows[i].ItemArray.GetValue(13) + "','" + dataTable.Rows[i].ItemArray.GetValue(14) + "')"; 

          cmd.ExecuteNonQuery(); 
         } 
         //close DB.connection 
         DBconn.Close(); 
        } 
       } 
      } 
     } 
     finally 
     { 

     } 
     return dataTable; 
    } 
+0

這看起來像一個緩慢而痛苦的RBAR。 – Fionnuala 2012-07-17 15:34:40