服务器之家

服务器之家 > 正文

手把手教你mvc导入excel

时间:2020-05-20 15:00     来源/作者:wangwangwangMax

准备工作:

1.在项目中添加对NPOI的引用,NPOI下载地址:http://npoi.codeplex.com/releases/view/38113

2.NPOI学习

NPOI下载,里面有五个dll,需要引用到你的项目,我这边用的mvc4+三层的方式架构的项目

我用的工具是(vs2012+sql2014)

准备工作做完,我们开始进入主题

1.前端页面,代码:

?
1
2
3
4
5
6
7
8
9
10
<div class="filebtn">
        @using (Html.BeginForm("importexcel", "foot", FormMethod.Post, new { enctype = "multipart/form-data" }))
          {
            <samp>请选择要上传的Excel文件:</samp>
            <span id="txt_Path"></span>
            <strong>选择文件<input name="file" type="file" id="file" /></strong>@*
            @Html.AntiForgeryToken() //防止跨站请求伪造(CSRF:Cross-site request forgery)攻击
           *@<input type="submit" id="ButtonUpload" value="提交"  class="offer"/>
          }
      </div>

2.接下来就是控制器

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public class footController : Controller
  {
    //
    // GET: /foot/
    private static readonly String Folder = "/files";
    public ActionResult excel()
    {
      return View();
    }
 
    /// 导入excel文档
    public ActionResult importexcel()
    {
      //1.接收客户端传过来的数据
      HttpPostedFileBase file = Request.Files["file"];
      if (file == null || file.ContentLength <= 0)
      {
        return Json("请选择要上传的Excel文件", JsonRequestBehavior.AllowGet);
      }
      //string filepath = Server.MapPath(Folder);
      //if (!Directory.Exists(filepath))
      //{
      //  Directory.CreateDirectory(filepath);
      //}
      //var fileName = Path.Combine(filepath, Path.GetFileName(file.FileName));
      // file.SaveAs(fileName);
      //获取一个streamfile对象,该对象指向一个上传文件,准备读取改文件的内容
      Stream streamfile = file.InputStream;
      DataTable dt = new DataTable();
      string FinName = Path.GetExtension(file.FileName);
      if (FinName != ".xls" && FinName != ".xlsx")
      {
        return Json("只能上传Excel文档",JsonRequestBehavior.AllowGet);
      }
      else
      {
        try
        {
          if (FinName == ".xls")
          {
            //创建一个webbook,对应一个Excel文件(用于xls文件导入类)
            HSSFWorkbook hssfworkbook = new HSSFWorkbook(streamfile);
            dt = excelDAL.ImExport(dt, hssfworkbook);
          }
          else
          {
            XSSFWorkbook hssfworkbook = new XSSFWorkbook(streamfile);
            dt = excelDAL.ImExport(dt, hssfworkbook);
          }
          return Json("",JsonRequestBehavior.AllowGet);
        }
        catch(Exception ex)
        {
          return Json("导入失败 !"+ex.Message, JsonRequestBehavior.AllowGet);
        }
    }
      
    }
 
}

3.业务逻辑层[excelDAL]

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.Data;
using NPOI.XSSF.UserModel;
 
namespace GJL.Compoent
{
  public class excelDAL
  {
    ///<summary>
    /// #region 两种不同版本的操作excel
    /// 扩展名*.xlsx
    /// </summary>
    public static DataTable ImExport(DataTable dt, XSSFWorkbook hssfworkbook)
    {
      NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
      System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
      for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)
      {
        dt.Columns.Add(sheet.GetRow(0).Cells[j].ToString());
      }
      while (rows.MoveNext())
      {
        XSSFRow row = (XSSFRow)rows.Current;
        DataRow dr = dt.NewRow();
        for (int i = 0; i < row.LastCellNum; i++)
        {
          NPOI.SS.UserModel.ICell cell = row.GetCell(i);
          if (cell == null)
          {
            dr[i] = null;
          }
          else
          {
            dr[i] = cell.ToString();
          }
        }
        dt.Rows.Add(dr);
      }
      dt.Rows.RemoveAt(0);
      if (dt!=null && dt.Rows.Count != 0)
      {
        for (int i = 0; i < dt.Rows.Count; i++)
        {
          string categary = dt.Rows[i]["页面"].ToString();
          string fcategary = dt.Rows[i]["分类"].ToString();
          string fTitle = dt.Rows[i]["标题"].ToString();
          string fUrl = dt.Rows[i]["链接"].ToString();
          FooterDAL.Addfoot(categary, fcategary, fTitle, fUrl);
        }
      }
      return dt;
    }
 
    #region 两种不同版本的操作excel
    ///<summary>
    /// 扩展名*.xls
    /// </summary>
    public static DataTable ImExport(DataTable dt, HSSFWorkbook hssfworkbook)
    {
      // 在webbook中添加一个sheet,对应Excel文件中的sheet,取出第一个工作表,索引是0
      NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
      System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
      for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)
      {
        dt.Columns.Add(sheet.GetRow(0).Cells[j].ToString());
      }
      while (rows.MoveNext())
      {
        HSSFRow row = (HSSFRow)rows.Current;
        DataRow dr = dt.NewRow();
        for (int i = 0; i < row.LastCellNum; i++)
        {
          NPOI.SS.UserModel.ICell cell = row.GetCell(i);
          if (cell == null)
          {
            dr[i] = null;
          }
          else
          {
            dr[i] = cell.ToString();
          }
        }
        dt.Rows.Add(dr);
      }
      dt.Rows.RemoveAt(0);
      if (dt != null && dt.Rows.Count != 0)
      {
        for (int i = 0; i < dt.Rows.Count; i++)
        {
          string categary = dt.Rows[i]["页面"].ToString();
          string fcategary = dt.Rows[i]["分类"].ToString();
          string fTitle = dt.Rows[i]["标题"].ToString();
          string fUrl = dt.Rows[i]["链接"].ToString();
          FooterDAL.Addfoot(categary, fcategary, fTitle, fUrl);
        }
 
      }
      return dt;
    }
    #endregion
  }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static partial class FooterDAL
  {
    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="id"></param>
    /// <param name="catgary"></param>
    /// <param name="fcatgary"></param>
    /// <param name="fTitle"></param>
    /// <param name="fUrl"></param>
    /// <returns></returns>
    public static int Addfoot(string categary, string fcategary, string fTitle, string fUrl)
    {
      string sql = string.Format("insert into Foot (categary,fcategary,fTitle,fUrl)values(@categary,@fcategary,@fTitle,@fUrl)");
      SqlParameter[] parm =
        {
           new SqlParameter("@categary",categary)
          ,new SqlParameter("@fcategary",fcategary)
          ,new SqlParameter("@fTitle",fTitle)
          ,new SqlParameter("@fUrl",fUrl)
        };
      return new DBHelperSQL<Foot>(CommonTool.dbname).ExcuteSql(sql,parm); 
    }
}

//FooterDAL将datatable,就是excel里面的数据添加到sql数据库

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/wangwangwangMax/p/7922119.html

标签:

相关文章

热门资讯

歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
超A是什么意思 你好a表达的是什么
超A是什么意思 你好a表达的是什么 2019-06-06
返回顶部