(准备)生成一个DataTable

 /// <summary>
/// 生成一个数据表
/// </summary>
/// <returns></returns>
static DataTable GetTable()
{
try
{
DataTable dt = new DataTable("Characters"); dt.Columns.Add("Column0");
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");
dt.Columns.Add("Column3"); dt.Rows.Add("abc", "def", "ghi", "jkl");
dt.Rows.Add("def", "ghi", "jkl", "mno");
dt.Rows.Add("ghi", "jkl", "mno", "pqr");
dt.Rows.Add("jkl", "mno", "pqr", "stu"); Console.WriteLine("Set DataTable: " + dt.TableName);
foreach (DataRow dr in dt.Rows)
{
foreach (object obj in dr.ItemArray)
{
Console.Write(obj.ToString() + " ");
}
Console.WriteLine();
}
Console.WriteLine("Mission complete!"); return dt;
}
catch
{
return null;
}
}

函数:将DataTable的内容输出到DBF文件

 /// <summary>
/// 将数据表写入到DBF文件中
/// </summary>
/// <param name="dt"></param>
static void WriteToDbf(DataTable dt)
{
Console.WriteLine("Writing to: " + dt.TableName + ".dbf ..."); //连接字符串
string sConn =
"Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=" + System.IO.Directory.GetCurrentDirectory() + "; " +
"Extended Properties=dBASE IV;";
OleDbConnection conn = new OleDbConnection(sConn);
conn.Open(); try
{
//如果存在同名文件则先删除
if (File.Exists(dt.TableName + ".dbf"))
{
Console.WriteLine("Delete file: " + dt.TableName + ".dbf ...");
File.Delete(dt.TableName + ".dbf");
} OleDbCommand cmd; //建立新表
StringBuilder sbCreate = new StringBuilder();
sbCreate.Append("CREATE TABLE " + dt.TableName + ".dbf (");
for (int i = ; i < dt.Columns.Count; i++)
{
sbCreate.Append(dt.Columns[i].ColumnName);
sbCreate.Append(" char(25)");
if (i != dt.Columns.Count - )
{
sbCreate.Append(", ");
}
else
{
sbCreate.Append(')');
}
} Console.WriteLine("\nCreating Table ...");
Console.WriteLine(sbCreate.ToString());
cmd = new OleDbCommand(sbCreate.ToString(), conn);
cmd.ExecuteNonQuery(); //插入各行
StringBuilder sbInsert = new StringBuilder();
foreach (DataRow dr in dt.Rows)
{
sbInsert.Clear();
sbInsert.Append("INSERT INTO " + dt.TableName + ".dbf (");
for (int i = ; i < dt.Columns.Count; i++)
{
sbInsert.Append(dt.Columns[i].ColumnName);
if (i != dt.Columns.Count - )
{
sbInsert.Append(", ");
}
}
sbInsert.Append(") VALUES (");
for (int i = ; i < dt.Columns.Count; i++)
{
sbInsert.Append("'" + dr[i].ToString() + "'");
if (i != dt.Columns.Count - )
{
sbInsert.Append(", ");
}
}
sbInsert.Append(')'); Console.WriteLine("\nInserting lines ...");
Console.WriteLine(sbInsert.ToString());
cmd = new OleDbCommand(sbInsert.ToString(), conn);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
} conn.Close();
}

Main函数中的调用

 static void Main(string[] args)
{
DataTable dt = GetTable(); //生成一个数据表
WriteToDbf(dt); //将数据表输出到DBF表中 Console.ReadLine();
7 }

运行结果

C# 将DataTable存储到DBF文件中-LMLPHP

转自:http://my.oschina.net/Tsybius2014/blog/282797

05-08 08:09