使用MVC .net Web应用程序将Excel工作表导入数据库

时间:2018-11-16 08:21:24

标签: excel asp.net-mvc

我是编程新手,我正尝试使用mvc将excel工作表导入数据库。我能够导入数据库,但是我需要找出如何添加验证(例如电子邮件和重复项)的方法。好像我两次上传相同的excel工作表,数据将两次导入到我的数据库中。我也想显示导入后更新的网页上的行数。我该怎么做 ?这是我的控制器代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.OleDb;
using System.IO;

命名空间excelimport.Controllers {     公共类HomeController:控制器     {

    // GET: /Home/
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
    OleDbConnection Econ;

    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        string filename = Guid.NewGuid() + Path.GetExtension(file.FileName);
        string filepath = "/excelfolder/" + filename;
        file.SaveAs(Path.Combine(Server.MapPath("/excelfolder"), filename));
        InsertExceldata(filepath, filename);
        return View();
    }

    private void ExcelConn(string filepath)
    {
        string constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", filepath);
        Econ = new OleDbConnection(constr);
    }

    private void InsertExceldata(string fileepath, string filename)
    {
        string fullpath = Server.MapPath("/excelfolder/") + filename;
        ExcelConn(fullpath);
        String query = string.Format("Select * from [{0}]", "Sheet1$");
        OleDbCommand Ecom = new OleDbCommand(query, Econ);
        Econ.Open();

        DataSet ds = new DataSet();
        OleDbDataAdapter oda = new OleDbDataAdapter(query, Econ);
        Econ.Close();
        oda.Fill(ds);

        DataTable dt =ds.Tables[0];

        SqlBulkCopy objbulk = new SqlBulkCopy(con)
        {
            DestinationTableName = "UserInformation"
        };
        objbulk.ColumnMappings.Add("Email", "Email");
        objbulk.ColumnMappings.Add("Name", "Name");
        objbulk.ColumnMappings.Add("PhoneNo", "PhoneNo");
        objbulk.ColumnMappings.Add("Address", "Address");
        objbulk.ColumnMappings.Add("ZipCode", "ZipCode");
        objbulk.ColumnMappings.Add("Country", "Country");
        objbulk.ColumnMappings.Add("State", "State");
        objbulk.ColumnMappings.Add("City", "City");
        con.Open();
        objbulk.WriteToServer(dt);
        con.Close();       }
}

}

0 个答案:

没有答案