[英]Asp net mvc : one Excel sheet with insert this data into SQL Server table using Asp net mvc
Insert excel data into sql server table using ASP.NET MVC. 使用ASP.NET MVC将Excel数据插入到SQL Server表中。 Error in in controller on this line:
products.WriteToServer(_product);
此行上的控制器中的错误:
products.WriteToServer(_product);
this is error message : 这是错误消息:
The given value of type String from the data source cannot be converted to type int of the specified target column.
来自数据源的String类型的给定值不能转换为指定目标列的int类型。
controller code: 控制器代码:
[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
string filePath = string.Empty;
if (postedFile != null)
{
string path = Server.MapPath("~/Uploads/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
filePath = path + Path.GetFileName(postedFile.FileName);
string extension = Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(filePath);
string conString = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03.
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 and above.
conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
DataTable dt = new DataTable();
// DataTable _dt = new DataTable();
// DataTable optionCategories = new DataTable();
// DataTable options = new DataTable();
DataTable _product = new DataTable();
conString = string.Format(conString, filePath);
using (OleDbConnection connExcel = new OleDbConnection(conString))
{
using (OleDbCommand cmdExcel = new OleDbCommand())
{
using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
{
cmdExcel.Connection = connExcel;
//Get the name of First Sheet.
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
// string sheetName1 = dtExcelSchema.Rows[1]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet.
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
odaExcel.SelectCommand = cmdExcel;
odaExcel.Fill(_product);
// cmdExcel.CommandText = "SELECT * From [" + sheetName1 + "]";
//odaExcel.Fill(_dt);
connExcel.Close();
}
}
}
conString = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlBulkCopy products = new SqlBulkCopy(con))
{
//Set the database table name.
products.DestinationTableName = "dbo.Products";
// [OPTIONAL]: Map the Excel columns with that of the database table
products.ColumnMappings.Clear();
products.ColumnMappings.Add("Id", "Id");
products.ColumnMappings.Add("Sku", "Sku");
products.ColumnMappings.Add("UPC", "UPC");
products.ColumnMappings.Add("Name", "Name");
products.ColumnMappings.Add("Price", "Price");
products.ColumnMappings.Add("CostPrice", "CostPrice");
products.ColumnMappings.Add("RetailPrice", "RetailPrice");
products.ColumnMappings.Add("SalePrice", "SalePrice");
products.ColumnMappings.Add("Weight", "Weight");
products.ColumnMappings.Add("Quantity", "Quantity");
products.ColumnMappings.Add("Description", "Description");
products.ColumnMappings.Add("Keywords", "Keywords");
products.ColumnMappings.Add("TaxClassId", "TaxClassId");
products.ColumnMappings.Add("IsFeatured", "IsFeatured");
products.ColumnMappings.Add("IsVisible", "IsVisible");
products.ColumnMappings.Add("AddQuantity", "AddQuantity");
products.ColumnMappings.Add("IsCustomOptionProduct", "IsCustomOptionProduct");
// products.ColumnMappings.Add("DrowingRefNo", "DrowingRefNo");
con.Open();
products.WriteToServer(_product);
con.Close();
}
}
}
return View();
}
}
}
---------sql server table script---------- --------- sql服务器表脚本----------
CREATE TABLE [dbo].[Products](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Sku] [nvarchar](100) NULL,
[UPC] [nvarchar](max) NULL,
[Name] [nvarchar](1000) NOT NULL,
[Price] [decimal](18, 2) NOT NULL,
[CostPrice] [decimal](18, 2) NULL,
[RetailPrice] [decimal](18, 2) NULL,
[SalePrice] [decimal](18, 2) NULL,
[Weight] [decimal](18, 2) NOT NULL,
[Quantity] [int] NULL,
[Description] [nvarchar](max) NULL,
[Keywords] [nvarchar](2000) NULL,
[TaxClassId] [int] NULL,
[IsFeatured] [bit] NOT NULL,
[IsVisible] [bit] NOT NULL,
[AddQuantity] [int] NULL,
[IsCustomOptionProduct] [bit] NOT NULL DEFAULT ((0)),
CONSTRAINT [PK_dbo.Products] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Products] WITH CHECK ADD CONSTRAINT [FK_dbo.Products_dbo.TaxClasses_TaxClassId] FOREIGN KEY([TaxClassId])
REFERENCES [dbo].[TaxClasses] ([Id])
GO
ALTER TABLE [dbo].[Products] CHECK CONSTRAINT `enter code here`[FK_dbo.Products_dbo.TaxClasses_TaxClassId]
GO
suggestion change column datatype like as below , where you are expecting datatype to be integer 建议更改列数据类型,如下所示,您期望数据类型为整数
Convert.ToInt32(dt.Columns["Product"]);
I suggest you create datatable in you code with propert types of your column and copy each row of datatable you are receiving from excelt to stongly type datatable. 我建议您在代码中使用列的属性类型创建数据表,并将接收到的数据表的每一行从excelt复制到严格类型的数据表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.