MVC excel导入

MVC excel导入

view部分
这里写图片描述

代码


@{
    Layout = "~/Views/Shared/_LayoutPage1.cshtml";
    ViewBag.Title = "Index";
}
<script src="~/scripts/jquery-1.10.2.js"></script>
<link rel="stylesheet" href="~/Content/kd.css" />

@using (Html.BeginForm("StationImport", "daoru", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    <h2  style="color:#fff;">
        信息导入
    </h2>

        <div class="daoru">
            <fieldset id="myfieldset1">

                <p>
                    选择文件:<input id="FileUpload" type="file" name="files" style="color:#fff;" />
                </p>                                                  
                <p>
                    <input id="btnImport" type="submit" value="导入" />
                </p>
                <span >@ViewBag.error</span>
            </fieldset>
        </div>
}

controller部分
这里写图片描述
这里写图片描述

代码
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Rjb.Models;

namespace Rjb.Controllers
{
public class daoruController : Controller
{
// GET: daoru
public rjbEntities ddb= new rjbEntities();
public ActionResult Index()
{
return View();
}

    [HttpPost]
    public ActionResult StationImport(HttpPostedFileBase filebase)
    {
        HttpPostedFileBase file = Request.Files["files"];//获取excel文件
        if (file == null || file.ContentLength <= 0)//判断是否为空
        {
            ViewBag.error = "文件不能为空";
            return View();
        }
        string fileExtenSion; //获取上传文件的扩展名
        fileExtenSion = Path.GetExtension(file.FileName);
        if (fileExtenSion.ToLower() != ".xls" && fileExtenSion.ToLower() != ".xlsx")
        {
            ViewBag.error = "文件类型不对,只能导入xls和xlsx格式的文件";
            return View();
        }
        string FileName = "../Content/excel" + Path.GetFileName(file.FileName);
        //删除服务器里上传的文件 
        if (System.IO.File.Exists(Server.MapPath(FileName)))
        {
            System.IO.File.Delete(Server.MapPath(FileName));
        }
        file.SaveAs(Server.MapPath(FileName));
        //HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES  
        string connstr2003 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(FileName) + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
        string connstr2007 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(FileName) + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
        OleDbConnection conn;
        if (fileExtenSion.ToLower() == ".xls")
        {
            conn = new OleDbConnection(connstr2003);
        }
        else
        {
            conn = new OleDbConnection(connstr2007);
        }
        conn.Open();
        string sql = "select * from [Sheet1$]";
        OleDbCommand cmd = new OleDbCommand(sql, conn);
        DataTable dt = new DataTable();
        OleDbDataReader sdr = cmd.ExecuteReader();

        dt.Load(sdr);
        sdr.Close();
        conn.Close();
        //删除服务器里上传的文件  
        if (System.IO.File.Exists(Server.MapPath(FileName)))
        {
            System.IO.File.Delete(Server.MapPath(FileName));
        }
        try
        {            
            int insertcount = 0;//记录插入成功条数  
            for (int i = 0; i < dt.Rows.Count; i++)  //列数
            {
                string e_name = dt.Rows[i][0].ToString();//获取编号
                t_shop shop = new t_shop();
                shop.s_name = e_name;
                ddb.t_shop.Add(shop);
                ddb.SaveChanges();                                                               
                    insertcount++;                  
            }
            Response.Write(insertcount + "条数据导入成功!");            
        }
        catch (Exception ex)
        {
        }          
        return RedirectToAction("Index");
    }







}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下步骤实现MVC+bootstrap实现Excel导入功能: 1. 在MVC项目中添加ExcelHelper类,用于读取Excel内容。 2. 在View视图中添加导入Excel的按钮和相关表单控件。 3. 在Controller中添加导入Excel文件的Action方法,通过HttpPostedFileBase参数获取上传的Excel文件。 4. 在Action方法中调用ExcelHelper类读取Excel内容,并将读取结果存储到Model中。 5. 在View视图中展示读取结果。 6. 使用Bootstrap的样式美化展示效果。 具体实现细节可以参考以下示例代码: ExcelHelper类: ```csharp public class ExcelHelper { public static DataTable ReadExcelFile(Stream stream) { IWorkbook workbook = null; ISheet sheet = null; DataTable data = new DataTable(); int startRow = 0; try { workbook = WorkbookFactory.Create(stream); sheet = workbook.GetSheetAt(0); if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue); data.Columns.Add(column); } startRow = sheet.FirstRowNum + 1; for (int i = startRow; i <= sheet.LastRowNum; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } } catch (Exception ex) { throw ex; } finally { sheet?.Dispose(); workbook?.Close(); } return data; } } ``` View视图: ```html @using (Html.BeginForm("Import", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" })) { <div class="form-group"> <label for="ExcelFile">选择Excel文件</label> <input type="file" name="ExcelFile" id="ExcelFile" class="form-control-file" accept=".xls,.xlsx"> </div> <button type="submit" class="btn btn-primary">导入</button> } @if (Model != null && Model.Rows.Count > 0) { <table class="table table-striped"> <thead> <tr> @foreach (DataColumn column in Model.Columns) { <th>@column.ColumnName</th> } </tr> </thead> <tbody> @foreach (DataRow row in Model.Rows) { <tr> @foreach (DataColumn column in Model.Columns) { <td>@row[column.ColumnName]</td> } </tr> } </tbody> </table> } ``` Controller: ```csharp public class ExcelController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Import(HttpPostedFileBase ExcelFile) { if (ExcelFile != null && ExcelFile.ContentLength > 0) { try { DataTable data = ExcelHelper.ReadExcelFile(ExcelFile.InputStream); return View(data); } catch (Exception ex) { ModelState.AddModelError("ExcelFile", "读取Excel文件时发生错误:" + ex.Message); } } else { ModelState.AddModelError("ExcelFile", "请选择Excel文件!"); } return View(); } } ``` 以上示例代码中,上传的Excel文件将通过HttpPostedFileBase参数传递到Controller的Import方法中,然后调用ExcelHelper类的ReadExcelFile方法读取Excel内容,并将读取结果存储到Model中,在View视图中展示读取结果。同时,使用Bootstrap的样式美化展示效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值