如何提取MDB文件';将表格内容转换为C#中的文本

本文关键字:转换 表格 文本 提取 何提取 MDB 文件 | 更新日期: 2023-09-27 18:29:20

我正在处理的一个项目包含一个MDB(acecss数据库)文件。我想将表的内容导出为文本,但很难找到一种使用C#轻松完成的方法。有没有比使用OLEDB和查询更快的方法?

更新:理想情况下,我不想静态地命名每个表(有数百个),并且我必须使用.NET 2.0或更低版本。

如何提取MDB文件';将表格内容转换为C#中的文本

可能有更有效的方法,但您可以将数据填充到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:

EDIT我还没有测试过,但类似的东西应该适用于.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());

脑海中没有明显的方法。只需编写一些遍历表的内容,并以您想要的任何文本格式(.csv、制表符分隔等)吐出数据。

你可以在Access中用VBA编写它,但我不知道这会让它更快还是更慢。

如果你想走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);
     }
 }