Files
MsAddIns/ExportExcelTest/Mdb.cs
2026-02-28 21:01:57 +08:00

139 lines
5.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using NCalc;
namespace ConsoleApp
{
internal class Mdb
{
static void Main(string[] args)
{
//var expr = new Expression("1 + 2");
//Func<int> f = expr.ToLambda<int>();
//Console.WriteLine(f()); // will print 3
//var expr = new Expression("([Param1] + 2)* [Param2]");
//Func<ExpressionContext, double> f = expr.ToLambda<ExpressionContext, double>();
//var context = new ExpressionContext { Param1 = 33.4, Param2 = 40.48 };
//Console.WriteLine(f(context)); // will print True
Dictionary<string, object> parameters = new Dictionary<string, object>() {
{"Param1", 413.5 },
{"Param3", 40.48}
};
var formula = "([Param1] + 2)* [Param2]";
var result = EvaluateFormula(formula, parameters);
Console.WriteLine(result);
}
public static double EvaluateFormula(string formula, Dictionary<string, object> parameters)
{
Expression e = new Expression(formula);
e.Parameters = parameters;
return Convert.ToDouble(e.Evaluate());
}
private static bool TestMBD()
{
Console.WriteLine("请输入MDB文件完整路径例如C:\\cs.mdb");
string mdbPath = Console.ReadLine();
mdbPath = @"D:\其他\地质\附件\和平站.mdb";
if (!File.Exists(mdbPath))
{
Console.WriteLine("文件不存在!");
return false;
}
// 检查是否为Access95 或Access97 MDB旧格式
// 如果太旧Jet或ACE也无法打开需要转换
if (IsOldAccessDatabase(mdbPath))
{
Console.WriteLine("检测到此MDB文件为非常老的Access版本 (如Access 95/97)OLEDB 不支持直接读取。建议使用 Access 打开并另存为 2000/2003 格式。或者使用专门的MDB转换工具。");
Console.ReadKey();
return false;
}
string[] providers = new[]
{
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath + ";",
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + mdbPath + ";Persist Security Info=False;"
};
foreach (var provider in providers)
{
Console.WriteLine($"尝试使用提供程序: {provider}");
try
{
ExportWithProvider(mdbPath, provider);
Console.WriteLine($"使用 {provider} 导出完成!\n===============================\n");
}
catch (Exception ex)
{
Console.WriteLine($"使用 {provider} 出错: {ex.Message}\n===============================\n");
}
}
Console.WriteLine("所有尝试完成如果依然失败请确认MDB文件格式是否过于陈旧。\n按任意键退出。");
Console.ReadKey();
return true;
}
static void ExportWithProvider(string mdbPath, string provider)
{
using (var conn = new OleDbConnection(provider))
{
conn.Open();
DataTable tables = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string outputDir = Path.Combine(Path.GetDirectoryName(mdbPath), "ExportedCSVs_" + (provider.Contains("Jet") ? "JET" : "ACE"));
Directory.CreateDirectory(outputDir);
foreach (DataRow row in tables.Rows)
{
string tableName = row["TABLE_NAME"].ToString();
Console.WriteLine($"导出表: {tableName}");
var cmd = new OleDbCommand($"SELECT * FROM [{tableName}]", conn);
var adapter = new OleDbDataAdapter(cmd);
var dt = new DataTable();
adapter.Fill(dt);
string csvFilePath = Path.Combine(outputDir, tableName + ".csv");
using (var writer = new StreamWriter(csvFilePath, false, System.Text.Encoding.UTF8))
{
writer.WriteLine(string.Join(",", dt.Columns.Cast<DataColumn>().Select(c => $"\"{c.ColumnName}\"")));
foreach (DataRow dr in dt.Rows)
{
var fields = dr.ItemArray.Select(field => $"\"{field?.ToString()?.Replace("\"", "\"\"") ?? ""}\"");
writer.WriteLine(string.Join(",", fields));
}
}
Console.WriteLine($"已导出: {csvFilePath}");
}
}
}
static bool IsOldAccessDatabase(string path)
{
// 检查文件头字节老MDB的文件头通常以0x00 0x01 0x00 0x00 开头
// 或者标识0x00 0x01 0x00 0x00 0x00 0x00
byte[] header = new byte[4];
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
fs.Read(header, 0, 4);
}
return header[0] == 0x00 && header[1] == 0x01;
}
}
}