【问题标题】:Copy CSV file to MS Access Table将 CSV 文件复制到 MS Access 表
【发布时间】:2012-07-15 12:17:27
【问题描述】:

使用 C# 我正在尝试创建一个控制台应用程序,该应用程序从特定文件夹位置读取 CSV 文件并将这些记录导入 MS Access 表。成功导入文件中的记录后,我将删除 .csv 文件。

到目前为止,这是我所拥有的:

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 DB 中创建的表吗?我该怎么做呢?任何帮助都会很棒

【问题讨论】:

    标签: c# ms-access csv import


    【解决方案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]
    

    【讨论】:

    • 你需要对连接msdn.microsoft.com/en-us/library/…执行sql,或者更好的是,使用命令并执行。
    • 我现在有我的代码从 CSV 文件中选择数据,我可以遍历每一行/列,但我不知道如何对 MS Access 进行实际插入/更新数据库。你能帮我解决这个问题吗? @Remou
    • 我在上面发布了 SQL,当针对连接运行时,会将 CSV 插入 Access 表或创建新的 Access 表。它不需要您从 CSV 中选择数据,这只是一步。
    【解决方案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;
        }
    

    【讨论】:

    • 这看起来像一个缓慢而痛苦的RBAR。
    猜你喜欢
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多