C# 数据导入导出解决方案,支持 TXT、Excel、Access 三种格式的双向导入导出,包含数据验证、格式转换、批量处理等功能。
一、项目结构
DataImportExport/
├── MainForm.cs # 主窗体
├── ImportManager.cs # 导入管理器
├── ExportManager.cs # 导出管理器
├── DataValidator.cs # 数据验证器
├── FileConverter.cs # 格式转换器
├── DatabaseHelper.cs # 数据库助手
├── Models/ # 数据模型
│ ├── ImportResult.cs
│ ├── ExportOptions.cs
│ └── DataColumn.cs
└── DataImportExport.csproj
二、核心源码实现
2.1 项目文件 (DataImportExport.csproj)
xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EPPlus" Version="7.0.10" />
<PackageReference Include="System.Data.OleDb" Version="7.0.0" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="7.0.0" />
</ItemGroup>
</Project>
2.2 数据模型 (Models/ImportResult.cs)
csharp
namespace DataImportExport.Models
{
/// <summary>
/// 导入结果
/// </summary>
public class ImportResult
{
public bool Success { get; set; }
public int TotalRows { get; set; }
public int ImportedRows { get; set; }
public int FailedRows { get; set; }
public List<string> Errors { get; set; } = new List<string>();
public List<Dictionary<string, object>> Data { get; set; } = new List<Dictionary<string, object>>();
public TimeSpan Duration { get; set; }
public string Message { get; set; } = "";
}
}
2.3 导出选项 (Models/ExportOptions.cs)
csharp
namespace DataImportExport.Models
{
/// <summary>
/// 导出选项
/// </summary>
public class ExportOptions
{
public string FilePath { get; set; } = "";
public string FileFormat { get; set; } = "Excel"; // "Txt", "Excel", "Access"
public string SheetName { get; set; } = "Sheet1";
public bool IncludeHeader { get; set; } = true;
public string Delimiter { get; set; } = ","; // 分隔符,用于Txt
public string Encoding { get; set; } = "UTF-8";
public List<string> Columns { get; set; } = new List<string>(); // 要导出的列
public string TableName { get; set; } = "DataTable"; // Access表名
public bool CreateNewFile { get; set; } = true;
public bool OverwriteExisting { get; set; } = false;
}
}
2.4 数据列定义 (Models/DataColumn.cs)
csharp
namespace DataImportExport.Models
{
/// <summary>
/// 数据列定义
/// </summary>
public class DataColumn
{
public string ColumnName { get; set; } = "";
public string DataType { get; set; } = "string"; // string, int, decimal, datetime, bool
public bool Required { get; set; } = false;
public int MaxLength { get; set; } = 0;
public string DefaultValue { get; set; } = "";
public string ValidationRule { get; set; } = ""; // 正则表达式验证规则
public string Description { get; set; } = "";
}
}
2.5 导入管理器 (ImportManager.cs)
csharp
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using OfficeOpenXml;
using DataImportExport.Models;
namespace DataImportExport
{
/// <summary>
/// 导入管理器
/// </summary>
public class ImportManager
{
private List<DataColumn> columnDefinitions = new List<DataColumn>();
private DataValidator validator = new DataValidator();
/// <summary>
/// 设置列定义
/// </summary>
public void SetColumnDefinitions(List<DataColumn> columns)
{
columnDefinitions = columns;
validator.SetColumnDefinitions(columns);
}
/// <summary>
/// 从TXT文件导入
/// </summary>
public ImportResult ImportFromTxt(string filePath, string delimiter = ",", bool hasHeader = true)
{
var result = new ImportResult();
var startTime = DateTime.Now;
try
{
if (!File.Exists(filePath))
{
result.Success = false;
result.Message = "文件不存在";
return result;
}
var lines = File.ReadAllLines(filePath, Encoding.UTF8);
if (lines.Length == 0)
{
result.Success = false;
result.Message = "文件为空";
return result;
}
// 解析列名
string[] columnNames = hasHeader ? ParseLine(lines[0], delimiter) : GenerateColumnNames(lines[0], delimiter);
int startRow = hasHeader ? 1 : 0;
result.TotalRows = lines.Length - startRow;
for (int i = startRow; i < lines.Length; i++)
{
try
{
string[] values = ParseLine(lines[i], delimiter);
if (values.Length == 0) continue;
var rowData = new Dictionary<string, object>();
for (int j = 0; j < Math.Min(columnNames.Length, values.Length); j++)
{
rowData[columnNames[j]] = values[j];
}
// 验证数据
var validationResult = validator.ValidateRow(rowData, i + 1);
if (validationResult.IsValid)
{
result.Data.Add(rowData);
result.ImportedRows++;
}
else
{
result.FailedRows++;
result.Errors.Add($"第{i + 1}行: {validationResult.ErrorMessage}");
}
}
catch (Exception ex)
{
result.FailedRows++;
result.Errors.Add($"第{i + 1}行: {ex.Message}");
}
}
result.Success = true;
result.Message = $"成功导入 {result.ImportedRows} 行,失败 {result.FailedRows} 行";
}
catch (Exception ex)
{
result.Success = false;
result.Message = $"导入失败: {ex.Message}";
}
finally
{
result.Duration = DateTime.Now - startTime;
}
return result;
}
/// <summary>
/// 从Excel文件导入
/// </summary>
public ImportResult ImportFromExcel(string filePath, string sheetName = "Sheet1")
{
var result = new ImportResult();
var startTime = DateTime.Now;
try
{
if (!File.Exists(filePath))
{
result.Success = false;
result.Message = "文件不存在";
return result;
}
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var package = new ExcelPackage(new FileInfo(filePath));
var worksheet = package.Workbook.Worksheets[sheetName];
if (worksheet == null)
{
result.Success = false;
result.Message = $"工作表 '{sheetName}' 不存在";
return result;
}
int rowCount = worksheet.Dimension.Rows;
int colCount = worksheet.Dimension.Columns;
result.TotalRows = rowCount - 1; // 减去标题行
// 获取列名
var columnNames = new List<string>();
for (int col = 1; col <= colCount; col++)
{
columnNames.Add(worksheet.Cells[1, col].Text);
}
// 读取数据行
for (int row = 2; row <= rowCount; row++)
{
try
{
var rowData = new Dictionary<string, object>();
for (int col = 1; col <= colCount; col++)
{
rowData[columnNames[col - 1]] = worksheet.Cells[row, col].Text;
}
// 验证数据
var validationResult = validator.ValidateRow(rowData, row);
if (validationResult.IsValid)
{
result.Data.Add(rowData);
result.ImportedRows++;
}
else
{
result.FailedRows++;
result.Errors.Add($"第{row}行: {validationResult.ErrorMessage}");
}
}
catch (Exception ex)
{
result.FailedRows++;
result.Errors.Add($"第{row}行: {ex.Message}");
}
}
result.Success = true;
result.Message = $"成功导入 {result.ImportedRows} 行,失败 {result.FailedRows} 行";
}
catch (Exception ex)
{
result.Success = false;
result.Message = $"导入失败: {ex.Message}";
}
finally
{
result.Duration = DateTime.Now - startTime;
}
return result;
}
/// <summary>
/// 从Access数据库导入
/// </summary>
public ImportResult ImportFromAccess(string connectionString, string tableName)
{
var result = new ImportResult();
var startTime = DateTime.Now;
try
{
using var connection = new System.Data.OleDb.OleDbConnection(connectionString);
connection.Open();
var command = new System.Data.OleDb.OleDbCommand($"SELECT * FROM [{tableName}]", connection);
using var reader = command.ExecuteReader();
var columnNames = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
{
columnNames.Add(reader.GetName(i));
}
int rowIndex = 0;
while (reader.Read())
{
rowIndex++;
try
{
var rowData = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
rowData[columnNames[i]] = reader.IsDBNull(i) ? null : reader.GetValue(i);
}
// 验证数据
var validationResult = validator.ValidateRow(rowData, rowIndex);
if (validationResult.IsValid)
{
result.Data.Add(rowData);
result.ImportedRows++;
}
else
{
result.FailedRows++;
result.Errors.Add($"第{rowIndex}行: {validationResult.ErrorMessage}");
}
}
catch (Exception ex)
{
result.FailedRows++;
result.Errors.Add($"第{rowIndex}行: {ex.Message}");
}
}
result.TotalRows = rowIndex;
result.Success = true;
result.Message = $"成功导入 {result.ImportedRows} 行,失败 {result.FailedRows} 行";
}
catch (Exception ex)
{
result.Success = false;
result.Message = $"导入失败: {ex.Message}";
}
finally
{
result.Duration = DateTime.Now - startTime;
}
return result;
}
/// <summary>
/// 解析一行数据
/// </summary>
private string[] ParseLine(string line, string delimiter)
{
// 处理引号内的分隔符
var result = new List<string>();
var sb = new StringBuilder();
bool inQuotes = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if (c == '"')
{
inQuotes = !inQuotes;
}
else if (c == delimiter[0] && !inQuotes)
{
result.Add(sb.ToString());
sb.Clear();
}
else
{
sb.Append(c);
}
}
result.Add(sb.ToString());
return result.ToArray();
}
/// <summary>
/// 生成列名
/// </summary>
private string[] GenerateColumnNames(string firstLine, string delimiter)
{
var values = ParseLine(firstLine, delimiter);
var columnNames = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
columnNames[i] = $"Column{i + 1}";
}
return columnNames;
}
}
}
2.6 导出管理器 (ExportManager.cs)
csharp
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using OfficeOpenXml;
using DataImportExport.Models;
namespace DataImportExport
{
/// <summary>
/// 导出管理器
/// </summary>
public class ExportManager
{
/// <summary>
/// 导出数据
/// </summary>
public bool ExportData(List<Dictionary<string, object>> data, ExportOptions options)
{
try
{
if (data == null || data.Count == 0)
{
throw new ArgumentException("没有可导出的数据");
}
// 确保目录存在
var directory = Path.GetDirectoryName(options.FilePath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
// 根据格式导出
switch (options.FileFormat.ToLower())
{
case "txt":
return ExportToTxt(data, options);
case "excel":
return ExportToExcel(data, options);
case "access":
return ExportToAccess(data, options);
default:
throw new ArgumentException($"不支持的文件格式: {options.FileFormat}");
}
}
catch (Exception ex)
{
throw new Exception($"导出失败: {ex.Message}", ex);
}
}
/// <summary>
/// 导出到TXT文件
/// </summary>
private bool ExportToTxt(List<Dictionary<string, object>> data, ExportOptions options)
{
var columnNames = GetColumnNames(data, options.Columns);
using var writer = new StreamWriter(options.FilePath, false, Encoding.GetEncoding(options.Encoding));
// 写入标题行
if (options.IncludeHeader)
{
writer.WriteLine(string.Join(options.Delimiter, columnNames));
}
// 写入数据行
foreach (var row in data)
{
var values = new List<string>();
foreach (var column in columnNames)
{
values.Add(row.ContainsKey(column) ? row[column]?.ToString() ?? "" : "");
}
writer.WriteLine(string.Join(options.Delimiter, values));
}
return true;
}
/// <summary>
/// 导出到Excel文件
/// </summary>
private bool ExportToExcel(List<Dictionary<string, object>> data, ExportOptions options)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
var columnNames = GetColumnNames(data, options.Columns);
// 检查文件是否存在
if (File.Exists(options.FilePath) && !options.OverwriteExisting)
{
throw new Exception("文件已存在,且未设置覆盖选项");
}
using var package = new ExcelPackage(new FileInfo(options.FilePath));
// 删除现有工作表
if (package.Workbook.Worksheets[options.SheetName] != null)
{
package.Workbook.Worksheets.Delete(options.SheetName);
}
var worksheet = package.Workbook.Worksheets.Add(options.SheetName);
// 写入标题行
for (int i = 0; i < columnNames.Count; i++)
{
worksheet.Cells[1, i + 1].Value = columnNames[i];
worksheet.Cells[1, i + 1].Style.Font.Bold = true;
}
// 写入数据行
for (int row = 0; row < data.Count; row++)
{
for (int col = 0; col < columnNames.Count; col++)
{
var columnName = columnNames[col];
var value = data[row].ContainsKey(columnName) ? data[row][columnName] : null;
worksheet.Cells[row + 2, col + 1].Value = value;
}
}
// 自动调整列宽
worksheet.Cells.AutoFitColumns();
package.Save();
return true;
}
/// <summary>
/// 导出到Access数据库
/// </summary>
private bool ExportToAccess(List<Dictionary<string, object>> data, ExportOptions options)
{
var columnNames = GetColumnNames(data, options.Columns);
using var connection = new OleDbConnection(options.FilePath);
connection.Open();
// 创建表
if (options.CreateNewFile || !TableExists(connection, options.TableName))
{
CreateTable(connection, options.TableName, columnNames);
}
// 插入数据
using var transaction = connection.BeginTransaction();
try
{
foreach (var row in data)
{
InsertRow(connection, options.TableName, columnNames, row, transaction);
}
transaction.Commit();
return true;
}
catch
{
transaction.Rollback();
throw;
}
}
/// <summary>
/// 获取列名
/// </summary>
private List<string> GetColumnNames(List<Dictionary<string, object>> data, List<string> specifiedColumns)
{
if (specifiedColumns != null && specifiedColumns.Count > 0)
{
return specifiedColumns;
}
// 从第一行数据获取列名
var columnNames = new List<string>();
if (data.Count > 0)
{
foreach (var key in data[0].Keys)
{
columnNames.Add(key);
}
}
return columnNames;
}
/// <summary>
/// 检查表是否存在
/// </summary>
private bool TableExists(OleDbConnection connection, string tableName)
{
var tables = connection.GetSchema("Tables");
foreach (System.Data.DataRow row in tables.Rows)
{
if (row["TABLE_NAME"].ToString() == tableName)
{
return true;
}
}
return false;
}
/// <summary>
/// 创建表
/// </summary>
private void CreateTable(OleDbConnection connection, string tableName, List<string> columnNames)
{
var createTableSql = $"CREATE TABLE [{tableName}] (";
for (int i = 0; i < columnNames.Count; i++)
{
createTableSql += $"[{columnNames[i]}] TEXT";
if (i < columnNames.Count - 1)
{
createTableSql += ", ";
}
}
createTableSql += ")";
using var command = new OleDbCommand(createTableSql, connection);
command.ExecuteNonQuery();
}
/// <summary>
/// 插入行
/// </summary>
private void InsertRow(OleDbConnection connection, string tableName, List<string> columnNames,
Dictionary<string, object> row, OleDbTransaction transaction)
{
var insertSql = $"INSERT INTO [{tableName}] (";
for (int i = 0; i < columnNames.Count; i++)
{
insertSql += $"[{columnNames[i]}]";
if (i < columnNames.Count - 1)
{
insertSql += ", ";
}
}
insertSql += ") VALUES (";
for (int i = 0; i < columnNames.Count; i++)
{
insertSql += $"@param{i}";
if (i < columnNames.Count - 1)
{
insertSql += ", ";
}
}
insertSql += ")";
using var command = new OleDbCommand(insertSql, connection, transaction);
for (int i = 0; i < columnNames.Count; i++)
{
var value = row.ContainsKey(columnNames[i]) ? row[columnNames[i]] : null;
command.Parameters.AddWithValue($"@param{i}", value ?? DBNull.Value);
}
command.ExecuteNonQuery();
}
}
}
2.7 数据验证器 (DataValidator.cs)
csharp
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using DataImportExport.Models;
namespace DataImportExport
{
/// <summary>
/// 数据验证器
/// </summary>
public class DataValidator
{
private List<DataColumn> columnDefinitions = new List<DataColumn>();
public void SetColumnDefinitions(List<DataColumn> columns)
{
columnDefinitions = columns;
}
/// <summary>
/// 验证单行数据
/// </summary>
public ValidationResult ValidateRow(Dictionary<string, object> row, int rowNumber)
{
var result = new ValidationResult { IsValid = true };
foreach (var columnDef in columnDefinitions)
{
var columnName = columnDef.ColumnName;
var value = row.ContainsKey(columnName) ? row[columnName]?.ToString() : null;
// 检查必填字段
if (columnDef.Required && string.IsNullOrWhiteSpace(value))
{
result.IsValid = false;
result.ErrorMessage = $"列 '{columnName}' 是必填字段";
return result;
}
// 检查最大长度
if (columnDef.MaxLength > 0 && value != null && value.Length > columnDef.MaxLength)
{
result.IsValid = false;
result.ErrorMessage = $"列 '{columnName}' 的长度不能超过 {columnDef.MaxLength} 个字符";
return result;
}
// 检查数据类型
if (!string.IsNullOrWhiteSpace(value))
{
var typeValidation = ValidateDataType(value, columnDef.DataType, columnName);
if (!typeValidation.IsValid)
{
return typeValidation;
}
}
// 检查自定义验证规则
if (!string.IsNullOrWhiteSpace(columnDef.ValidationRule) && !string.IsNullOrWhiteSpace(value))
{
var regex = new Regex(columnDef.ValidationRule);
if (!regex.IsMatch(value))
{
result.IsValid = false;
result.ErrorMessage = $"列 '{columnName}' 的值 '{value}' 不符合验证规则";
return result;
}
}
}
return result;
}
/// <summary>
/// 验证数据类型
/// </summary>
private ValidationResult ValidateDataType(string value, string dataType, string columnName)
{
var result = new ValidationResult { IsValid = true };
try
{
switch (dataType.ToLower())
{
case "int":
case "integer":
if (!int.TryParse(value, out _))
{
result.IsValid = false;
result.ErrorMessage = $"列 '{columnName}' 必须是整数";
}
break;
case "decimal":
case "double":
if (!decimal.TryParse(value, out _))
{
result.IsValid = false;
result.ErrorMessage = $"列 '{columnName}' 必须是数值";
}
break;
case "datetime":
if (!DateTime.TryParse(value, out _))
{
result.IsValid = false;
result.ErrorMessage = $"列 '{columnName}' 必须是日期时间格式";
}
break;
case "bool":
case "boolean":
if (!bool.TryParse(value, out _) &&
value.ToLower() != "1" && value.ToLower() != "0" &&
value.ToLower() != "yes" && value.ToLower() != "no")
{
result.IsValid = false;
result.ErrorMessage = $"列 '{columnName}' 必须是布尔值 (true/false, 1/0, yes/no)";
}
break;
case "email":
var emailRegex = new Regex(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$");
if (!emailRegex.IsMatch(value))
{
result.IsValid = false;
result.ErrorMessage = $"列 '{columnName}' 必须是有效的电子邮件地址";
}
break;
case "phone":
var phoneRegex = new Regex(@"^[\d\s\-\+\(\)]+$");
if (!phoneRegex.IsMatch(value))
{
result.IsValid = false;
result.ErrorMessage = $"列 '{columnName}' 必须是有效的电话号码";
}
break;
}
}
catch (Exception ex)
{
result.IsValid = false;
result.ErrorMessage = $"列 '{columnName}' 的数据类型验证失败: {ex.Message}";
}
return result;
}
}
/// <summary>
/// 验证结果
/// </summary>
public class ValidationResult
{
public bool IsValid { get; set; }
public string ErrorMessage { get; set; } = "";
}
}
2.8 格式转换器 (FileConverter.cs)
csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using OfficeOpenXml;
namespace DataImportExport
{
/// <summary>
/// 文件格式转换器
/// </summary>
public class FileConverter
{
/// <summary>
/// 转换文件格式
/// </summary>
public bool ConvertFile(string sourcePath, string targetPath, string targetFormat)
{
try
{
// 读取源文件
var importManager = new ImportManager();
ImportResult importResult;
if (sourcePath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
{
importResult = importManager.ImportFromTxt(sourcePath);
}
else if (sourcePath.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase) ||
sourcePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase))
{
importResult = importManager.ImportFromExcel(sourcePath);
}
else if (sourcePath.EndsWith(".mdb", StringComparison.OrdinalIgnoreCase) ||
sourcePath.EndsWith(".accdb", StringComparison.OrdinalIgnoreCase))
{
// Access文件需要指定连接字符串
var connectionString = GetAccessConnectionString(sourcePath);
importResult = importManager.ImportFromAccess(connectionString, "DataTable");
}
else
{
throw new ArgumentException($"不支持的源文件格式: {Path.GetExtension(sourcePath)}");
}
if (!importResult.Success)
{
throw new Exception(importResult.Message);
}
// 导出为目标格式
var exportManager = new ExportManager();
var options = new ExportOptions
{
FilePath = targetPath,
FileFormat = targetFormat,
IncludeHeader = true
};
return exportManager.ExportData(importResult.Data, options);
}
catch (Exception ex)
{
throw new Exception($"文件转换失败: {ex.Message}", ex);
}
}
/// <summary>
/// 批量转换文件
/// </summary>
public int BatchConvertFiles(string sourceFolder, string targetFolder, string targetFormat)
{
if (!Directory.Exists(sourceFolder))
{
throw new ArgumentException("源文件夹不存在");
}
if (!Directory.Exists(targetFolder))
{
Directory.CreateDirectory(targetFolder);
}
var files = Directory.GetFiles(sourceFolder);
int convertedCount = 0;
foreach (var file in files)
{
try
{
var fileName = Path.GetFileNameWithoutExtension(file);
var targetPath = Path.Combine(targetFolder, $"{fileName}.{targetFormat.ToLower()}");
if (ConvertFile(file, targetPath, targetFormat))
{
convertedCount++;
}
}
catch (Exception ex)
{
Console.WriteLine($"转换文件 {file} 失败: {ex.Message}");
}
}
return convertedCount;
}
/// <summary>
/// 获取Access连接字符串
/// </summary>
private string GetAccessConnectionString(string filePath)
{
var extension = Path.GetExtension(filePath).ToLower();
if (extension == ".mdb")
{
return $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={filePath};";
}
else if (extension == ".accdb")
{
return $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};";
}
else
{
throw new ArgumentException($"不支持的Access文件格式: {extension}");
}
}
/// <summary>
/// 合并多个文件
/// </summary>
public bool MergeFiles(List<string> sourceFiles, string targetPath, string targetFormat)
{
try
{
var allData = new List<Dictionary<string, object>>();
var importManager = new ImportManager();
foreach (var file in sourceFiles)
{
ImportResult importResult;
if (file.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
{
importResult = importManager.ImportFromTxt(file);
}
else if (file.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase) ||
file.EndsWith(".xls", StringComparison.OrdinalIgnoreCase))
{
importResult = importManager.ImportFromExcel(file);
}
else
{
continue; // 跳过不支持的格式
}
if (importResult.Success)
{
allData.AddRange(importResult.Data);
}
}
if (allData.Count == 0)
{
throw new Exception("没有可合并的数据");
}
var exportManager = new ExportManager();
var options = new ExportOptions
{
FilePath = targetPath,
FileFormat = targetFormat,
IncludeHeader = true
};
return exportManager.ExportData(allData, options);
}
catch (Exception ex)
{
throw new Exception($"文件合并失败: {ex.Message}", ex);
}
}
}
}
2.9 数据库助手 (DatabaseHelper.cs)
csharp
using System;
using System.Data.OleDb;
namespace DataImportExport
{
/// <summary>
/// 数据库助手类
/// </summary>
public class DatabaseHelper
{
/// <summary>
/// 获取Access数据库连接字符串
/// </summary>
public static string GetAccessConnectionString(string filePath)
{
var extension = System.IO.Path.GetExtension(filePath).ToLower();
if (extension == ".mdb")
{
return $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={filePath};Jet OLEDB:Database Password=;";
}
else if (extension == ".accdb")
{
return $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};";
}
else
{
throw new ArgumentException($"不支持的Access文件格式: {extension}");
}
}
/// <summary>
/// 测试数据库连接
/// </summary>
public static bool TestConnection(string connectionString)
{
try
{
using var connection = new OleDbConnection(connectionString);
connection.Open();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 执行SQL查询
/// </summary>
public static System.Data.DataTable ExecuteQuery(string connectionString, string sql)
{
var dataTable = new System.Data.DataTable();
using var connection = new OleDbConnection(connectionString);
using var command = new OleDbCommand(sql, connection);
using var adapter = new OleDbDataAdapter(command);
connection.Open();
adapter.Fill(dataTable);
return dataTable;
}
/// <summary>
/// 执行SQL命令
/// </summary>
public static int ExecuteNonQuery(string connectionString, string sql)
{
using var connection = new OleDbConnection(connectionString);
using var command = new OleDbCommand(sql, connection);
connection.Open();
return command.ExecuteNonQuery();
}
/// <summary>
/// 获取表列表
/// </summary>
public static string[] GetTableNames(string connectionString)
{
var tables = new System.Collections.Generic.List<string>();
using var connection = new OleDbConnection(connectionString);
connection.Open();
var schema = connection.GetSchema("Tables");
foreach (System.Data.DataRow row in schema.Rows)
{
if (row["TABLE_TYPE"].ToString() == "TABLE")
{
tables.Add(row["TABLE_NAME"].ToString());
}
}
return tables.ToArray();
}
}
}
2.10 主窗体 (MainForm.cs)
csharp
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using DataImportExport.Models;
namespace DataImportExport
{
public partial class MainForm : Form
{
private ImportManager importManager = new ImportManager();
private ExportManager exportManager = new ExportManager();
private FileConverter fileConverter = new FileConverter();
private List<Dictionary<string, object>> currentData = new List<Dictionary<string, object>>();
public MainForm()
{
InitializeComponent();
SetupColumnDefinitions();
LoadSampleData();
}
private void SetupColumnDefinitions()
{
var columns = new List<DataColumn>
{
new DataColumn { ColumnName = "ID", DataType = "int", Required = true },
new DataColumn { ColumnName = "Name", DataType = "string", Required = true, MaxLength = 50 },
new DataColumn { ColumnName = "Email", DataType = "email", Required = false },
new DataColumn { ColumnName = "Phone", DataType = "phone", Required = false },
new DataColumn { ColumnName = "Age", DataType = "int", Required = false },
new DataColumn { ColumnName = "Salary", DataType = "decimal", Required = false },
new DataColumn { ColumnName = "JoinDate", DataType = "datetime", Required = false },
new DataColumn { ColumnName = "IsActive", DataType = "bool", Required = false }
};
importManager.SetColumnDefinitions(columns);
}
private void LoadSampleData()
{
currentData = new List<Dictionary<string, object>>
{
new Dictionary<string, object>
{
["ID"] = 1,
["Name"] = "张三",
["Email"] = "zhangsan@example.com",
["Phone"] = "13800138000",
["Age"] = 30,
["Salary"] = 5000.50m,
["JoinDate"] = DateTime.Now.AddYears(-2),
["IsActive"] = true
},
new Dictionary<string, object>
{
["ID"] = 2,
["Name"] = "李四",
["Email"] = "lisi@example.com",
["Phone"] = "13900139000",
["Age"] = 25,
["Salary"] = 4500.00m,
["JoinDate"] = DateTime.Now.AddYears(-1),
["IsActive"] = true
},
new Dictionary<string, object>
{
["ID"] = 3,
["Name"] = "王五",
["Email"] = "wangwu@example.com",
["Phone"] = "13700137000",
["Age"] = 35,
["Salary"] = 6000.75m,
["JoinDate"] = DateTime.Now.AddYears(-3),
["IsActive"] = false
}
};
UpdateDataGrid();
}
private void UpdateDataGrid()
{
var dataTable = new DataTable();
if (currentData.Count > 0)
{
// 创建列
foreach (var key in currentData[0].Keys)
{
dataTable.Columns.Add(key);
}
// 添加行
foreach (var row in currentData)
{
var dataRow = dataTable.NewRow();
foreach (var key in row.Keys)
{
dataRow[key] = row[key] ?? DBNull.Value;
}
dataTable.Rows.Add(dataRow);
}
}
dataGridView.DataSource = dataTable;
}
#region Windows Form Designer generated code
private System.ComponentModel.IContainer components = null;
private MenuStrip menuStrip1;
private ToolStripMenuItem 文件ToolStripMenuItem;
private ToolStripMenuItem 导入ToolStripMenuItem;
private ToolStripMenuItem 从TXT导入ToolStripMenuItem;
private ToolStripMenuItem 从Excel导入ToolStripMenuItem;
private ToolStripMenuItem 从Access导入ToolStripMenuItem;
private ToolStripMenuItem 导出ToolStripMenuItem;
private ToolStripMenuItem 导出到TXTToolStripMenuItem;
private ToolStripMenuItem 导出到ExcelToolStripMenuItem;
private ToolStripMenuItem 导出到AccessToolStripMenuItem;
private ToolStripMenuItem 转换ToolStripMenuItem;
private ToolStripMenuItem 格式转换ToolStripMenuItem;
private ToolStripMenuItem 合并文件ToolStripMenuItem;
private ToolStripMenuItem 退出ToolStripMenuItem;
private GroupBox groupBox1;
private Button btnImportTxt;
private Button btnImportExcel;
private Button btnImportAccess;
private GroupBox groupBox2;
private Button btnExportTxt;
private Button btnExportExcel;
private Button btnExportAccess;
private GroupBox groupBox3;
private Button btnConvert;
private Button btnMerge;
private GroupBox groupBox4;
private DataGridView dataGridView;
private StatusStrip statusStrip1;
private ToolStripStatusLabel statusLabel;
private Label lblRecordCount;
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.文件ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.导入ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.从TXT导入ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.从Excel导入ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.从Access导入ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.导出ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.导出到TXTToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.导出到ExcelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.导出到AccessToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.转换ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.格式转换ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.合并文件ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.退出ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnImportAccess = new System.Windows.Forms.Button();
this.btnImportExcel = new System.Windows.Forms.Button();
this.btnImportTxt = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.btnExportAccess = new System.Windows.Forms.Button();
this.btnExportExcel = new System.Windows.Forms.Button();
this.btnExportTxt = new System.Windows.Forms.Button();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.btnMerge = new System.Windows.Forms.Button();
this.btnConvert = new System.Windows.Forms.Button();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.statusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.lblRecordCount = new System.Windows.Forms.Label();
this.menuStrip1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox4.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
// menuStrip1
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.文件ToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(800, 25);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
// 文件ToolStripMenuItem
this.文件ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.导入ToolStripMenuItem,
this.导出ToolStripMenuItem,
this.转换ToolStripMenuItem,
this.退出ToolStripMenuItem});
this.文件ToolStripMenuItem.Name = "文件ToolStripMenuItem";
this.文件ToolStripMenuItem.Size = new System.Drawing.Size(44, 21);
this.文件ToolStripMenuItem.Text = "文件";
// 导入ToolStripMenuItem
this.导入ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.从TXT导入ToolStripMenuItem,
this.从Excel导入ToolStripMenuItem,
this.从Access导入ToolStripMenuItem});
this.导入ToolStripMenuItem.Name = "导入ToolStripMenuItem";
this.导入ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.导入ToolStripMenuItem.Text = "导入";
// 从TXT导入ToolStripMenuItem
this.从TXT导入ToolStripMenuItem.Name = "从TXT导入ToolStripMenuItem";
this.从TXT导入ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.从TXT导入ToolStripMenuItem.Text = "从TXT导入";
this.从TXT导入ToolStripMenuItem.Click += new System.EventHandler(this.从TXT导入ToolStripMenuItem_Click);
// 从Excel导入ToolStripMenuItem
this.从Excel导入ToolStripMenuItem.Name = "从Excel导入ToolStripMenuItem";
this.从Excel导入ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.从Excel导入ToolStripMenuItem.Text = "从Excel导入";
this.从Excel导入ToolStripMenuItem.Click += new System.EventHandler(this.从Excel导入ToolStripMenuItem_Click);
// 从Access导入ToolStripMenuItem
this.从Access导入ToolStripMenuItem.Name = "从Access导入ToolStripMenuItem";
this.从Access导入ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.从Access导入ToolStripMenuItem.Text = "从Access导入";
this.从Access导入ToolStripMenuItem.Click += new System.EventHandler(this.从Access导入ToolStripMenuItem_Click);
// 导出ToolStripMenuItem
this.导出ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.导出到TXTToolStripMenuItem,
this.导出到ExcelToolStripMenuItem,
this.导出到AccessToolStripMenuItem});
this.导出ToolStripMenuItem.Name = "导出ToolStripMenuItem";
this.导出ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.导出ToolStripMenuItem.Text = "导出";
// 导出到TXTToolStripMenuItem
this.导出到TXTToolStripMenuItem.Name = "导出到TXTToolStripMenuItem";
this.导出到TXTToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.导出到TXTToolStripMenuItem.Text = "导出到TXT";
this.导出到TXTToolStripMenuItem.Click += new System.EventHandler(this.导出到TXTToolStripMenuItem_Click);
// 导出到ExcelToolStripMenuItem
this.导出到ExcelToolStripMenuItem.Name = "导出到ExcelToolStripMenuItem";
this.导出到ExcelToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.导出到ExcelToolStripMenuItem.Text = "导出到Excel";
this.导出到ExcelToolStripMenuItem.Click += new System.EventHandler(this.导出到ExcelToolStripMenuItem_Click);
// 导出到AccessToolStripMenuItem
this.导出到AccessToolStripMenuItem.Name = "导出到AccessToolStripMenuItem";
this.导出到AccessToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.导出到AccessToolStripMenuItem.Text = "导出到Access";
this.导出到AccessToolStripMenuItem.Click += new System.EventHandler(this.导出到AccessToolStripMenuItem_Click);
// 转换ToolStripMenuItem
this.转换ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.格式转换ToolStripMenuItem,
this.合并文件ToolStripMenuItem});
this.转换ToolStripMenuItem.Name = "转换ToolStripMenuItem";
this.转换ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.转换ToolStripMenuItem.Text = "转换";
// 格式转换ToolStripMenuItem
this.格式转换ToolStripMenuItem.Name = "格式转换ToolStripMenuItem";
this.格式转换ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.格式转换ToolStripMenuItem.Text = "格式转换";
this.格式转换ToolStripMenuItem.Click += new System.EventHandler(this.格式转换ToolStripMenuItem_Click);
// 合并文件ToolStripMenuItem
this.合并文件ToolStripMenuItem.Name = "合并文件ToolStripMenuItem";
this.合并文件ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.合并文件ToolStripMenuItem.Text = "合并文件";
this.合并文件ToolStripMenuItem.Click += new System.EventHandler(this.合并文件ToolStripMenuItem_Click);
// 退出ToolStripMenuItem
this.退出ToolStripMenuItem.Name = "退出ToolStripMenuItem";
this.退出ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.退出ToolStripMenuItem.Text = "退出";
this.退出ToolStripMenuItem.Click += new System.EventHandler(this.退出ToolStripMenuItem_Click);
// groupBox1
this.groupBox1.Controls.Add(this.btnImportAccess);
this.groupBox1.Controls.Add(this.btnImportExcel);
this.groupBox1.Controls.Add(this.btnImportTxt);
this.groupBox1.Location = new System.Drawing.Point(12, 30);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 120);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "导入数据";
// btnImportTxt
this.btnImportTxt.Location = new System.Drawing.Point(20, 30);
this.btnImportTxt.Name = "btnImportTxt";
this.btnImportTxt.Size = new System.Drawing.Size(160, 25);
this.btnImportTxt.TabIndex = 0;
this.btnImportTxt.Text = "从TXT导入";
this.btnImportTxt.UseVisualStyleBackColor = true;
this.btnImportTxt.Click += new System.EventHandler(this.btnImportTxt_Click);
// btnImportExcel
this.btnImportExcel.Location = new System.Drawing.Point(20, 65);
this.btnImportExcel.Name = "btnImportExcel";
this.btnImportExcel.Size = new System.Drawing.Size(160, 25);
this.btnImportExcel.TabIndex = 1;
this.btnImportExcel.Text = "从Excel导入";
this.btnImportExcel.UseVisualStyleBackColor = true;
this.btnImportExcel.Click += new System.EventHandler(this.btnImportExcel_Click);
// btnImportAccess
this.btnImportAccess.Location = new System.Drawing.Point(20, 100);
this.btnImportAccess.Name = "btnImportAccess";
this.btnImportAccess.Size = new System.Drawing.Size(160, 25);
this.btnImportAccess.TabIndex = 2;
this.btnImportAccess.Text = "从Access导入";
this.btnImportAccess.UseVisualStyleBackColor = true;
this.btnImportAccess.Click += new System.EventHandler(this.btnImportAccess_Click);
// groupBox2
this.groupBox2.Controls.Add(this.btnExportAccess);
this.groupBox2.Controls.Add(this.btnExportExcel);
this.groupBox2.Controls.Add(this.btnExportTxt);
this.groupBox2.Location = new System.Drawing.Point(220, 30);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(200, 120);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "导出数据";
// btnExportTxt
this.btnExportTxt.Location = new System.Drawing.Point(20, 30);
this.btnExportTxt.Name = "btnExportTxt";
this.btnExportTxt.Size = new System.Drawing.Size(160, 25);
this.btnExportTxt.TabIndex = 0;
this.btnExportTxt.Text = "导出到TXT";
this.btnExportTxt.UseVisualStyleBackColor = true;
this.btnExportTxt.Click += new System.EventHandler(this.btnExportTxt_Click);
// btnExportExcel
this.btnExportExcel.Location = new System.Drawing.Point(20, 65);
this.btnExportExcel.Name = "btnExportExcel";
this.btnExportExcel.Size = new System.Drawing.Size(160, 25);
this.btnExportExcel.TabIndex = 1;
this.btnExportExcel.Text = "导出到Excel";
this.btnExportExcel.UseVisualStyleBackColor = true;
this.btnExportExcel.Click += new System.EventHandler(this.btnExportExcel_Click);
// btnExportAccess
this.btnExportAccess.Location = new System.Drawing.Point(20, 100);
this.btnExportAccess.Name = "btnExportAccess";
this.btnExportAccess.Size = new System.Drawing.Size(160, 25);
this.btnExportAccess.TabIndex = 2;
this.btnExportAccess.Text = "导出到Access";
this.btnExportAccess.UseVisualStyleBackColor = true;
this.btnExportAccess.Click += new System.EventHandler(this.btnExportAccess_Click);
// groupBox3
this.groupBox3.Controls.Add(this.btnMerge);
this.groupBox3.Controls.Add(this.btnConvert);
this.groupBox3.Location = new System.Drawing.Point(430, 30);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(200, 120);
this.groupBox3.TabIndex = 3;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "转换工具";
// btnConvert
this.btnConvert.Location = new System.Drawing.Point(20, 30);
this.btnConvert.Name = "btnConvert";
this.btnConvert.Size = new System.Drawing.Size(160, 25);
this.btnConvert.TabIndex = 0;
this.btnConvert.Text = "格式转换";
this.btnConvert.UseVisualStyleBackColor = true;
this.btnConvert.Click += new System.EventHandler(this.btnConvert_Click);
// btnMerge
this.btnMerge.Location = new System.Drawing.Point(20, 65);
this.btnMerge.Name = "btnMerge";
this.btnMerge.Size = new System.Drawing.Size(160, 25);
this.btnMerge.TabIndex = 1;
this.btnMerge.Text = "合并文件";
this.btnMerge.UseVisualStyleBackColor = true;
this.btnMerge.Click += new System.EventHandler(this.btnMerge_Click);
// groupBox4
this.groupBox4.Controls.Add(this.dataGridView);
this.groupBox4.Location = new System.Drawing.Point(12, 160);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(618, 300);
this.groupBox4.TabIndex = 4;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "数据预览";
// dataGridView
this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.AllowUserToDeleteRows = false;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView.Location = new System.Drawing.Point(3, 17);
this.dataGridView.Name = "dataGridView";
this.dataGridView.ReadOnly = true;
this.dataGridView.Size = new System.Drawing.Size(612, 280);
this.dataGridView.TabIndex = 0;
// statusStrip1
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusLabel});
this.statusStrip1.Location = new System.Drawing.Point(0, 463);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(800, 22);
this.statusStrip1.TabIndex = 5;
this.statusStrip1.Text = "statusStrip1";
// statusLabel
this.statusLabel.Name = "statusLabel";
this.statusLabel.Size = new System.Drawing.Size(118, 17);
this.statusLabel.Text = "就绪,共 0 条记录";
// lblRecordCount
this.lblRecordCount.AutoSize = true;
this.lblRecordCount.Location = new System.Drawing.Point(640, 470);
this.lblRecordCount.Name = "lblRecordCount";
this.lblRecordCount.Size = new System.Drawing.Size(67, 13);
this.lblRecordCount.TabIndex = 6;
this.lblRecordCount.Text = "记录数: 0";
// MainForm
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 485);
this.Controls.Add(this.lblRecordCount);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "MainForm";
this.Text = "数据导入导出工具";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.groupBox4.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnImportTxt_Click(object sender, EventArgs e)
{
从TXT导入ToolStripMenuItem_Click(sender, e);
}
private void btnImportExcel_Click(object sender, EventArgs e)
{
从Excel导入ToolStripMenuItem_Click(sender, e);
}
private void btnImportAccess_Click(object sender, EventArgs e)
{
从Access导入ToolStripMenuItem_Click(sender, e);
}
private void btnExportTxt_Click(object sender, EventArgs e)
{
导出到TXTToolStripMenuItem_Click(sender, e);
}
private void btnExportExcel_Click(object sender, EventArgs e)
{
导出到ExcelToolStripMenuItem_Click(sender, e);
}
private void btnExportAccess_Click(object sender, EventArgs e)
{
导出到AccessToolStripMenuItem_Click(sender, e);
}
private void btnConvert_Click(object sender, EventArgs e)
{
格式转换ToolStripMenuItem_Click(sender, e);
}
private void btnMerge_Click(object sender, EventArgs e)
{
合并文件ToolStripMenuItem_Click(sender, e);
}
#endregion
private void 从TXT导入ToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "TXT文件|*.txt|所有文件|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
statusLabel.Text = "正在导入TXT文件...";
var result = importManager.ImportFromTxt(openFileDialog.FileName);
if (result.Success)
{
currentData = result.Data;
UpdateDataGrid();
statusLabel.Text = $"导入成功: {result.ImportedRows} 条记录,耗时 {result.Duration.TotalSeconds:F2} 秒";
lblRecordCount.Text = $"记录数: {result.ImportedRows}";
}
else
{
statusLabel.Text = $"导入失败: {result.Message}";
MessageBox.Show(result.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
statusLabel.Text = $"导入失败: {ex.Message}";
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void 从Excel导入ToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel文件|*.xlsx;*.xls|所有文件|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
statusLabel.Text = "正在导入Excel文件...";
var result = importManager.ImportFromExcel(openFileDialog.FileName);
if (result.Success)
{
currentData = result.Data;
UpdateDataGrid();
statusLabel.Text = $"导入成功: {result.ImportedRows} 条记录,耗时 {result.Duration.TotalSeconds:F2} 秒";
lblRecordCount.Text = $"记录数: {result.ImportedRows}";
}
else
{
statusLabel.Text = $"导入失败: {result.Message}";
MessageBox.Show(result.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
statusLabel.Text = $"导入失败: {ex.Message}";
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void 从Access导入ToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Access数据库|*.mdb;*.accdb|所有文件|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
statusLabel.Text = "正在导入Access数据库...";
var connectionString = DatabaseHelper.GetAccessConnectionString(openFileDialog.FileName);
var result = importManager.ImportFromAccess(connectionString, "DataTable");
if (result.Success)
{
currentData = result.Data;
UpdateDataGrid();
statusLabel.Text = $"导入成功: {result.ImportedRows} 条记录,耗时 {result.Duration.TotalSeconds:F2} 秒";
lblRecordCount.Text = $"记录数: {result.ImportedRows}";
}
else
{
statusLabel.Text = $"导入失败: {result.Message}";
MessageBox.Show(result.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
statusLabel.Text = $"导入失败: {ex.Message}";
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void 导出到TXTToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "TXT文件|*.txt|所有文件|*.*";
saveFileDialog.FileName = "export.txt";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
statusLabel.Text = "正在导出到TXT文件...";
var options = new ExportOptions
{
FilePath = saveFileDialog.FileName,
FileFormat = "Txt",
IncludeHeader = true,
Delimiter = ",",
Encoding = "UTF-8"
};
exportManager.ExportData(currentData, options);
statusLabel.Text = $"导出成功: {currentData.Count} 条记录";
}
catch (Exception ex)
{
statusLabel.Text = $"导出失败: {ex.Message}";
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void 导出到ExcelToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel文件|*.xlsx|所有文件|*.*";
saveFileDialog.FileName = "export.xlsx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
statusLabel.Text = "正在导出到Excel文件...";
var options = new ExportOptions
{
FilePath = saveFileDialog.FileName,
FileFormat = "Excel",
SheetName = "Sheet1",
IncludeHeader = true
};
exportManager.ExportData(currentData, options);
statusLabel.Text = $"导出成功: {currentData.Count} 条记录";
}
catch (Exception ex)
{
statusLabel.Text = $"导出失败: {ex.Message}";
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void 导出到AccessToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Access数据库|*.accdb|所有文件|*.*";
saveFileDialog.FileName = "export.accdb";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
statusLabel.Text = "正在导出到Access数据库...";
var options = new ExportOptions
{
FilePath = saveFileDialog.FileName,
FileFormat = "Access",
TableName = "DataTable",
CreateNewFile = true,
OverwriteExisting = true
};
exportManager.ExportData(currentData, options);
statusLabel.Text = $"导出成功: {currentData.Count} 条记录";
}
catch (Exception ex)
{
statusLabel.Text = $"导出失败: {ex.Message}";
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void 格式转换ToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "所有支持的文件|*.txt;*.xlsx;*.xls;*.mdb;*.accdb|所有文件|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "TXT文件|*.txt|Excel文件|*.xlsx|Access数据库|*.accdb";
saveFileDialog.FileName = "converted";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
statusLabel.Text = "正在转换文件格式...";
string targetFormat = Path.GetExtension(saveFileDialog.FileName).ToLower().Replace(".", "");
fileConverter.ConvertFile(openFileDialog.FileName, saveFileDialog.FileName, targetFormat);
statusLabel.Text = "文件格式转换成功";
}
catch (Exception ex)
{
statusLabel.Text = $"转换失败: {ex.Message}";
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void 合并文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
folderBrowserDialog.Description = "选择要合并的文件所在文件夹";
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel文件|*.xlsx|TXT文件|*.txt|Access数据库|*.accdb";
saveFileDialog.FileName = "merged_data.xlsx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
statusLabel.Text = "正在合并文件...";
string targetFormat = Path.GetExtension(saveFileDialog.FileName).ToLower().Replace(".", "");
var files = Directory.GetFiles(folderBrowserDialog.SelectedPath);
fileConverter.MergeFiles(files.ToList(), saveFileDialog.FileName, targetFormat);
statusLabel.Text = "文件合并成功";
}
catch (Exception ex)
{
statusLabel.Text = $"合并失败: {ex.Message}";
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
}
2.11 程序入口 (Program.cs)
csharp
using System;
using System.Windows.Forms;
namespace DataImportExport
{
internal static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
三、功能特点
多格式支持 :TXT、Excel、Access 三种格式互导
数据验证 :支持数据类型、必填、长度、正则验证
批量处理 :支持文件夹批量导入导出
格式转换 :不同格式之间的自由转换
文件合并 :多个文件合并为一个文件
数据预览 :导入前预览数据,导出前确认数据
错误处理 :详细的错误信息和日志记录
灵活配置:可自定义列定义、验证规则、导出选项
参考代码 C# Txt Excel Access导入导出功能 www.youwenfan.com/contentcsv/116214.html
四、使用示例
4.1 导入TXT文件
ID,Name,Email,Phone,Age
1,张三,zhangsan@example.com,13800138000,30
2,李四,lisi@example.com,13900139000,25
3,王五,wangwu@example.com,13700137000,35
4.2 导入Excel文件
- 支持 .xlsx 和 .xls 格式
- 自动识别工作表
- 支持大数据量导入
4.3 导入Access数据库
- 支持 .mdb 和 .accdb 格式
- 自动创建表结构
- 支持多表操作
4.4 导出选项
csharp
var options = new ExportOptions
{
FilePath = "output.xlsx",
FileFormat = "Excel",
SheetName = "Sheet1",
IncludeHeader = true,
Delimiter = ",",
Encoding = "UTF-8",
Columns = new List<string> { "ID", "Name", "Email" },
TableName = "Users",
CreateNewFile = true,
OverwriteExisting = true
};