mvc导入excel到数据库(不经过JavaScript)

          excel导入到数据库,这个步骤是什么?

          html接收到excel,后台代码接收到excel,判断格式,(xls和xlsx)。

          逐行找到各个列的信息,赋值给类的字段。

           进行数据库添加!

看一下html代码

    <body style="overflow-y:scroll;">  
          @* 这里的DataImportAll代表类,importExcel代表方法,其中btnImport中的submit属性就和importExcel方法关联,点击就会触发importExcel方法*@
     @using (Html.BeginForm("DataImportAll", "importExcel", FormMethod.Post, new { enctype = "multipart/form-data", id = "form1" }))  
    {    
          
            <div style="margin-top: 20px; font-size:12px; width:80%; padding-left:20px;">  
                <fieldset id="myfieldset1">  
                    <legend>物料数据导入</legend>  
                    <p>  
                        选择文件:   
                        <input id="FileUpload" type="file" name="FileUpload" style="width: 250px; height: 24px; background: White" />  
                        <input id="btnImport" type="submit" value="上传" style="width: 60px; height: 24px;"/>  
                    </p>  
                    <p style="color: Red; text-align: center;">@ViewBag.error</p>  @* 提示信息(成功或失败)*@
                </fieldset>  
            </div>  
              
        }  
       
    </body>

 
        //将Excel导入数据库
        [HttpPost]
        public ActionResult DataImportAll(HttpPostedFileBase filebase)
        {
            HttpPostedFileBase file = Request.Files["FileUpload"];//获取上传的文件
           
        
           if (file==null || file.ContentLength<0 || file.FileName=="")
           {
               ViewBag.error = "文件不能为空";
               return View("Index");
           }
           else
           {
               //检查文件的后缀名
               string filename = Path.GetFileName(file.FileName);
               string fileEx = System.IO.Path.GetExtension(filename);
               //得到需要的后缀名
               string FileType = ".xls,xlsx";
               if (!FileType.Contains(fileEx))
               {
                    ViewBag.error = "文件格式不正确";
                    return View("Index");
               }
               Stream inputStream = file.InputStream;

               XSSFWorkbook hssfworkbook = new XSSFWorkbook(inputStream);

              // HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputStream);
               NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);//第一个sheet

               int rowCount = sheet.LastRowNum;
               bool flage=false;
               for (int i = (sheet.FirstRowNum+1); i <=rowCount; i++)
               {
                   IRow row = sheet.GetRow(i);
                   t_user user = new t_user();
                   if (row!=null)
                   {
                      
                       if (row.GetCell(0)!=null)
                       {
                           user.userID = row.GetCell(0).ToString();
                           user.userName = row.GetCell(1).ToString();
                           flage = true;
                       }
                   }
               }
               if (flage==true)
               {
                   ViewBag.error = "导入成功!";
                   return View("Index");
               }
               else
               {
                   ViewBag.error = "导入失败!";
                   return View("Index");
               }
              
           }


        }
看一下命名空间

其中还需要引用NPOI 2.2.1 binary package的几个dll。才能在命名空间上写出。下载地址 http://npoi.codeplex.com/downloads/get/1476595

using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Data.OleDb;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using EF_Model;
using NPOI.XSSF.UserModel;
如果是xlsx需要引用
using NPOI.XSSF.UserModel;
其中要声明这个类

  XSSFWorkbook hssfworkbook = new XSSFWorkbook(inputStream);

如果是xls需要引用

using NPOI.HSSF.UserModel;
其中要声明这个类

 HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputStream);

谢谢大家的意见。




          

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 146
    评论
ASP.NET MVC导入Excel文件到数据库功能可以通过以下步骤实现: 1. 创建一个控制器和视图来上传Excel文件。 2. 使用第三方库如EPPlus来解析Excel文件并将其转换为数据表。 3. 使用ADO.NET连接到数据库并将数据表中的数据插入到数据库中。 以下是一个示例控制器和视图的代码: 控制器: ``` public class ExcelController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Import(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { string fileName = Path.GetFileName(file.FileName); string fileExtension = Path.GetExtension(fileName); if (fileExtension == ".xls" || fileExtension == ".xlsx") { string filePath = Server.MapPath("~/Content/" + fileName); file.SaveAs(filePath); DataTable dt = ReadExcelFile(filePath); InsertDataIntoDatabase(dt); return RedirectToAction("Index"); } else { ViewBag.Message = "Please upload a valid Excel file."; return View("Index"); } } else { ViewBag.Message = "Please select an Excel file to upload."; return View("Index"); } } private DataTable ReadExcelFile(string filePath) { using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; DataTable dt = new DataTable(); bool hasHeaderRow = true; foreach (var firstRowCell in worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column]) { dt.Columns.Add(hasHeaderRow ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column)); } int startRow = hasHeaderRow ? 2 : 1; for (int rowNum = startRow; rowNum <= worksheet.Dimension.End.Row; rowNum++) { var wsRow = worksheet.Cells[rowNum, 1, rowNum, worksheet.Dimension.End.Column]; DataRow row = dt.Rows.Add(); foreach (var cell in wsRow) { row[cell.Start.Column - 1] = cell.Text; } } return dt; } } private void InsertDataIntoDatabase(DataTable dt) { string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = "INSERT INTO MyTable (Column1, Column2, Column3) VALUES (@Column1, @Column2, @Column3)"; foreach (DataRow row in dt.Rows) { command.Parameters.AddWithValue("@Column1", row["Column1"]); command.Parameters.AddWithValue("@Column2", row["Column2"]); command.Parameters.AddWithValue("@Column3", row["Column3"]); command.ExecuteNonQuery(); command.Parameters.Clear(); } } } } ``` 视图: ``` @{ ViewBag.Title = "Import Excel File"; } <h2>Import Excel File</h2> @using (Html.BeginForm("Import", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-group"> <label for="file">Select Excel File:</label> <input type="file" name="file" id="file" /> </div> <button type="submit" class="btn btn-primary">Import</button> <div class="alert alert-danger" role="alert">@ViewBag.Message</div> } ```
评论 146
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值