簡體   English   中英

如何將MDB文件的表內容提取為C#中的文本?

[英]How can I extract an MDB file's table contents to text in C#?

我正在處理的項目包含一個MDB(acecss數據庫)文件。 我想將表的內容導出為文本,但是很難找到一種使用C#輕松實現的方法。 有沒有比使用OLEDB和查詢更快的方法?

更新:理想情況下,我不需要靜態地命名每個表(有數百個表),而必須使用.NET 2.0或更低版本。

沒有明顯的方法想到。 只需編寫一些遍歷表的內容,然后以所需的任何文本格式(.csv,制表符分隔等)吐出數據。

您總是可以在Access的VBA中編寫它,但是我不知道這會使它變快還是變慢。

也許有一種更有效的方法,但是您可以將數據填充到DataTable ,然后導出到文本文件:

DataTable獲取到DataTable

string connString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\\marcelo.accdb";

DataTable results = new DataTable();

using(OleDbConnection conn = new OleDbConnection(connString))
{
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM Clientes", conn);
    conn.Open();
    OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
    adapter.Fill(results);
}

DataTable導出為CSV:

編輯我還沒有測試過,但是類似的東西應該適用於.NET 2.0。

//initialize the strinbuilder
StringBuilder sb = new StringBuilder();    

//append the columns to the header row
string[] columns = new string[dt.Columns.Count - 1];
for (int i = 0; i < dt.Columns.Count; i++)
    columns[i] = dt.Columns[i].ColumnName;
sb.AppendLine(string.Join(",", columns));          

foreach (DataRow row in dt.Rows)
{
    //append the data for each row in the table
    string[] fields = new string[row.ItemArray.Length];
    for (int x = 0; x < myDataRow.ItemArray.Length; x++)        
        arr[x] = row[x].ToString();                
    sb.AppendLine(string.Join(",", fields));
}

File.WriteAllText("test.csv", sb.ToString());

如果要走Interop路線,可以使用Access TransferText方法在一個命令中完成:

using Access = Microsoft.Office.Interop.Access;
using System.Runtime.InteropServices;

static void ExportToCsv(string databasePath, string tableName, string csvFile) {
    Access.Application app = new Access.Application();
    app.OpenCurrentDatabase(databasePath);
    Access.DoCmd doCmd = app.DoCmd;
    doCmd.TransferText(Access.AcTextTransferType.acExportDelim, Type.Missing, tableName, csvFile, true);
    app.CloseCurrentDatabase();
    Marshal.FinalReleaseComObject(doCmd);
    doCmd = null; 
    app.Quit();
    Marshal.FinalReleaseComObject(app);
    app = null;
}

我不知道C#,但這是另一個想法,但是很粗糙。 它使用Microsoft.Office.Interop.Access.Dao

 DBEngine dbEng = new DBEngine();
 Workspace ws = dbEng.CreateWorkspace("", "admin", "", 
    WorkspaceTypeEnum.dbUseJet);
 Database db = ws.OpenDatabase("z:\\docs\\test.accdb", false, false, "");

 foreach (TableDef tdf in db.TableDefs)
 {
     string tablename=tdf.Name;
     if (tablename.Substring(0,4) != "MSys")
     {
         string sSQL = "SELECT * INTO [Text;FMT=Delimited;HDR=Yes;DATABASE=Z:\\Docs].[out_" 
            + tablename + ".csv] FROM " + tablename;
         db.Execute(sSQL);
     }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM