简体   繁体   English

ASP.NET MVC:一个Excel工作表,使用ASP.NET MVC将此数据插入到SQL Server表中

[英]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.

相关问题 使用ASP.NET MVC将Excel数据插入SQL Server - Insert Excel data to SQL server using ASP.NET MVC 使用 ASP.NET MVC 将 Excel 数据导入 SQL Server - Importing Excel data into SQL Server using ASP.NET MVC ASP.NET MVC显示SQL Server表数据 - ASP.NET MVC Display SQL Server table data How to insert HTML table data into SQL Server in a single batch by using jquery ajax and structured parameter with ASP.NET MVC controller - How to insert HTML table data into SQL Server in a single batch by using jquery ajax and structured parameter with ASP.NET MVC controller 在asp.net mvc中的Excel工作表中导出表视图 - Export the Table View in an Excel sheet in asp.net mvc 用数据 asp.net mvc 填充 Excel 表 - filling an excel sheet with data asp.net mvc 使用ASP.NET MVC中的验证将记录从Excel工作表导入SQL Server - Import records from Excel sheet into SQL Server with validations in ASP.NET MVC 使用ASP.NET MVC从记事本文件中读取数据并存储到SQL Server中的表中 - Read Data from Notepad File and Store into a Table in SQL Server using ASP.NET MVC 如何在一个表中插入多行? (MVC 5 ASP.NET) - How to Insert Multiple Rows in One Table? (MVC 5 ASP.NET) 如何使用ASP.NET MVC在按钮单击上导出Excel工作表中的数据 - How to export data in a Excel Sheet on a button click using ASP.NET MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM