我正在尝试将一些数据从 Excel 文件导出到 MDF 数据库。为此,我使用 Excel Data Reader 和 SQL Bulk Copy:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Excel;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
namespace BulkTest
{
class Program
{
static void Main(string[] args)
{
FileStream fs = File.Open(@"C:\Users\maarab\Desktop\List_Personnel 2013.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
DataTable dt = CreateDataTable();
string cx = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DataTest.mdf;Integrated Security=True;User Instance=True";
SqlBulkCopy bcp = new SqlBulkCopy(cx, SqlBulkCopyOptions.KeepIdentity);
bool first = true;
while (excelReader.Read())
{
if (first)
{
first = false;
}
else
{
if (String.IsNullOrWhiteSpace(excelReader.GetString(0)))
break;
else
{
string numNat = excelReader.GetString(2);
DateTime birthDate = excelReader.GetDateTime(9);
DateTime startDate = excelReader.GetDateTime(1);
if (!String.IsNullOrWhiteSpace(numNat))
{
if (numNat.Length == 12)
{
numNat = numNat.Remove(6, 1);
}
}
if (birthDate.Year < 1753)
birthDate = DateTime.Now;
if (startDate.Year < 1753)
startDate = DateTime.Now;
dt.Rows.Add(excelReader.GetString(0), excelReader.GetString(0), numNat, startDate, birthDate);
}
}
}
bcp.DestinationTableName = "person";
bcp.BatchSize = 100;
bcp.ColumnMappings.Add(0, 1);
bcp.ColumnMappings.Add(1, 2);
bcp.ColumnMappings.Add(2, 3);
bcp.ColumnMappings.Add(3, 4);
bcp.ColumnMappings.Add(4, 5);
try
{
bcp.WriteToServer(dt, DataRowState.Unchanged);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
public static DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("FirstName", typeof(string));
dt.Columns.Add("LastName", typeof(string));
dt.Columns.Add("NumNat", typeof(string));
dt.Columns.Add("Birthdate", typeof(DateTime));
dt.Columns.Add("StartDate", typeof(DateTime));
return dt;
}
}
}
我正在用我的 Excel 文件填充数据表,一切顺利。该程序运行没有问题,但不幸的是我的表中没有插入。有什么办法解决这个问题吗?