如何将MDB文件的表内容提取为C#中的文本? [英] How can I extract an MDB file's table contents to text in C#?
问题描述
我正在处理的项目包含一个MDB(acecss数据库)文件.我想将表的内容导出为文本,但是很难找到一种使用C#轻松实现的方法.有没有比使用OLEDB和查询更快的方法?
A project I'm working on contains an MDB (acecss database) file. I'd like to export the contents of the tables to text, but am having a hard time finding a way to do it easily using C#. Is there a faster way than using OLEDB and queries?
更新: 理想情况下,我不需要静态命名每个表(有数百个表),而必须使用.NET 2.0或更低版本.
Update: Ideally I'd like to not have to statically name each table (there are hundreds) and I have to use .NET 2.0 or below.
推荐答案
也许有一种更有效的方法,但是您可以将数据填充到DataTable
中,然后导出到文本文件:
There might be a more efficient way, but you could populate the data into a DataTable
, and then export to a text file:
将数据获取到DataTable
:
Getting data into the 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:
Exporting the DataTable
to CSV:
编辑,我还没有测试过,但是类似的东西应该适用于.NET 2.0.
EDIT I haven't tested this, but something like this should work for .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());
这篇关于如何将MDB文件的表内容提取为C#中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!