C#实现读取Excel文件并将数据写入数据库和DataTable

  using Spire.Xls;

  using System.Data.OleDb;

  class Program

  {

  static void Main(string[] args)

  {

  // 设置Excel文件路径

  string excelFilePath = "Sample.xlsx";

  // 设置Access数据库文件路径

  string accessDbFilePath = "Sample.accdb";

  // 加载Excel文件

  Workbook workbook = new Workbook();

  workbook.LoadFromFile(excelFilePath);

  // 获取第一个工作表

  Worksheet worksheet = workbook.Worksheets[0];

  // 使用工作表名称作为表名

  string tableName = worksheet.Name;

  // 获取第一行作为列名

  CellRange headerRange = worksheet.Rows[0];

  string[] columnNames = new string[headerRange.Columns.Length];

  for (int i = 0; i < headerRange.Columns.Length; i++)

  {

  columnNames[i] = headerRange.Columns[i].Value.Replace(" ", "_");

  }

  // 连接到Access数据库

  string connectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={accessDbFilePath};Persist Security Info=False;";

  using (OleDbConnection connection = new OleDbConnection(connectionString))

  {

  connection.Open();

  // 创建表

  string createTableQuery = $"CREATE TABLE [{tableName}] ({string.Join(", ", columnNames.Select(c => $"[{c}] Memo"))})";

  using (OleDbCommand createTableCommand = new OleDbCommand(createTableQuery, connection))

  {

  createTableCommand.ExecuteNonQuery();

  }

  // 插入数据

  string insertQuery = $"INSERT INTO [{tableName}] ({string.Join(", ", columnNames.Select(c => $"[{c}]"))}) VALUES ({string.Join(", ", columnNames.Select(c => $"@{c}"))})";

  using (OleDbCommand insertCommand = new OleDbCommand(insertQuery, connection))

  {

  foreach (CellRange row in worksheet.Rows.Cast().Skip(1))

  {

  for (int i = 0; i < row.Columns.Length; i++)

  {

  insertCommand.Parameters.AddWithValue($"@{columnNames[i]}", row.Columns[i].Value);

  }

  insertCommand.ExecuteNonQuery();

  insertCommand.Parameters.Clear();

  }

  }

  connection.Close();

  workbook.Dispose();

  }

  }

  }