Sql bulkcopy错误 - 给定的ColumnMapping与源或目标中的任何列都不匹配

时间:2015-01-29 08:01:40

标签: c# asp.net asp.net-mvc sqlbulkcopy npoi

我正在尝试将sqlbulkcopy添加到我的sql表中。我的数据源源有三列,目标表有四列,第一列是idendity列。将记录插入数据库时​​,目标表将生成值。我正在接受"给定的ColumnMapping与源或目标中的任何列都不匹配"在以下代码行。 sqlBulkCopy.WriteToServer(dtExcelData);我不明白是什么问题。

目标表数据类型如下

Id(int), AccountNumber(varchar 9), 金额(小数11,2), Sedol(nvarchar 30)

XSSFWorkbook xssfwb;
            using (FileStream file = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
            {
                xssfwb = new XSSFWorkbook(file);
            }


            var sheet = xssfwb.GetSheetAt(0); // Change this to the worksheet you want to import.
            var rows = sheet.GetRowEnumerator();
            var dtExcelData = new DataTable();
            var linenumber = 0;
            DataRow dr;



            dtExcelData.Columns.AddRange(new DataColumn[3] { 
            new DataColumn("AccountNumber", typeof(string)),
            new DataColumn("Amount", typeof(decimal)),
            new DataColumn("Sedol",typeof(string)) });



            while (rows.MoveNext())
            {
                IRow row = (XSSFRow)rows.Current;
                linenumber++;


                row.GetCell(4).SetCellType(CellType.Numeric);

                if (row.GetCell(0) != null)
                {
                    dr = dtExcelData.NewRow();
                    dr["AccountNumber"] = row.GetCell(1).ToString();
                    //dr["Amount"] = decimal.Parse(row.GetCell(4).ToString());
                    dr["Amount"] = (decimal)row.GetCell(4).NumericCellValue;
                        dr["Sedol"] = row.GetCell(11).ToString();


                    dtExcelData.Rows.Add(dr);
                }
            }

            DealingContext.ExecuteCommand("TRUNCATE TABLE [dbDealing].[MESSAGING].[Rebate]");



            //Set the database table name
            //using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(DealingContext.Connection.ConnectionString,SqlBulkCopyOptions.KeepIdentity))
            using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(DealingContext.Connection.ConnectionString))
            {
                sqlBulkCopy.DestinationTableName = "[dbDealing].[MESSAGING].[Rebate]";


                //[OPTIONAL]: Map the Excel columns with that of the database table
                sqlBulkCopy.ColumnMappings.Add("AccountNumber", "Owning Account ID");
                sqlBulkCopy.ColumnMappings.Add("Amount", "Amount");
                sqlBulkCopy.ColumnMappings.Add("Sedol", "Related Asset Identifier value");
                sqlBulkCopy.WriteToServer(dtExcelData);

            }

1 个答案:

答案 0 :(得分:0)

我曾经遇到过你的问题。

首先使用这个课程(它不是我的。我很久以前在互联网上发现了这个并且修改了一点),第二个确保你填写正确的表格。

 public static class BulkCopy
{
    public static DataTable ToDataTable<T>(List<T> data)
    {
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();

        if (IdentityColumnName != null)
        {
            if (IdentityColumnType == "int")
                table.Columns.Add(IdentityColumnName, typeof(Int32));
            else if (IdentityColumnType == "string")
                table.Columns.Add(IdentityColumnName, typeof(string));
        }

        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }


        if (IdentityColumnName != null)
        {
            object[] values = new object[props.Count + 1];
            foreach (T item in data)
            {
                for (int i = 1; i < values.Length; i++)
                {
                    values[i] = props[i - 1].GetValue(item) ?? DBNull.Value;
                }

                table.Rows.Add(values);
            }
        }
        else
        {
            object[] values = new object[props.Count];
            foreach (T item in data)
            {
                int i = 0;
                for (i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item) ?? DBNull.Value;
                }

                table.Rows.Add(values);
            }
        }
        return table;
    }

    public static void BulkSqlInsert<T>(List<T> list, string tableName,string connectionString)
    {
        if (list == null)
            throw new Exception("List of " + typeof(T).ToString() + " is null!");

        BulkCopy.BulkSqlInsert(BulkCopy.ToDataTable<T>(list), tableName, connectionString);
    }

    public static void BulkSqlInsert(DataTable dt, string tableName, string connectionString)
    {
        if (dt.Rows.Count == 0)
            return;

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlBulkCopy bulkCopy =
                new SqlBulkCopy
                (
                connection,
                SqlBulkCopyOptions.TableLock |
                SqlBulkCopyOptions.FireTriggers |
                SqlBulkCopyOptions.UseInternalTransaction,
                null
                );


            bulkCopy.DestinationTableName = tableName;

            connection.Open();


            bulkCopy.WriteToServer(dt);
            connection.Close();
        }
    }

    public static string IdentityColumnName { get; set; }

    public static string IdentityColumnType { get; set; }//string or int


}

示例:

你的桌子(CAR)有3列颜色和重量,一个标识栏可以说是ID。

创建此类:

  public class BulkCopyCar
{
    public string Color { get; set; }

    public string Weight{ get; set; }
 }

填充BulkCopyCar:

 List<BulkCopyCar> bulkCopyCarList = new List<BulkCopyCar>();
            bulkCopyCarList.Add(new BulkCopyCar() { Color = "Red", Weight = 155 });
            bulkCopyCarList.Add(new BulkCopyCar() { Color = "Blue", Weight = 400 });

插入数据库:

 BulkCopy.IdentityColumnName = "ID";
            BulkCopy.IdentityColumnType = "int";
            BulkCopy.BulkSqlInsert(bulkCopyCarList, "CAR", SQLConnectionString);

如果您没有使用标识列,请使用以下行:

BulkCopy.BulkSqlInsert(bulkCopyCarList, "CAR", SQLConnectionString);