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

前端代码

<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> excel

控制器

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"];//file对应前端选择文件的name属性
if (file == null || file.ContentLength <= )
{
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);
}
} } }
footController.cs

业务逻辑层

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();
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
for (int j = ; j < (sheet.GetRow().LastCellNum); j++)
{
dt.Columns.Add(sheet.GetRow().Cells[j].ToString());
}
while (rows.MoveNext())
{
XSSFRow row = (XSSFRow)rows.Current;
DataRow dr = dt.NewRow();
for (int i = ; 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();
if (dt!=null && dt.Rows.Count != )
{
for (int i = ; 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();
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
for (int j = ; j < (sheet.GetRow().LastCellNum); j++)
{
dt.Columns.Add(sheet.GetRow().Cells[j].ToString());
}
while (rows.MoveNext())
{
HSSFRow row = (HSSFRow)rows.Current;
DataRow dr = dt.NewRow();
for (int i = ; 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();
if (dt != null && dt.Rows.Count != )
{
for (int i = ; 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
}
} excelDAL

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

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

MVC中Excel导入的更多相关文章

  1. JeeSite中Excel导入导出

    在各种管理系统中,数据的导入导出是经常用到的功能,通常导入导出以Excel.CSV格式居多.如果是学习的过程中,最好是自己实现数据导入与导出的功能,然而在项目中,还是调用现成的功能比较好.近期一直使用 ...

  2. Java中Excel导入功能实现、excel导入公共方法_POI -

    这是一个思路希望能帮助到大家:如果大家有更好的解决方法希望分享出来 公司导入是这样做的 每个到导入的地方 @Override public List<DataImportMessage> ...

  3. java中excel导入\导出工具类

    1.导入工具 package com.linrain.jcs.test; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import ...

  4. vue中excel导入导出组件

    vue中导入导出excel,并根据后台返回类型进行判断,导入到数据库中 功能:实现js导入导出excel,并且对导入的excel进行展示,当excel标题名称和数据库的名称标题匹配时,则对应列导入的数 ...

  5. C#中excel导入sql

    using Microsoft.Office.Interop.Excel; public int ledinExcel(string file, object sender, EventArgs e) ...

  6. asp.net 中excel 导入数据库

    protected void Button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(Sy ...

  7. 在Asp.Net MVC中使用NPOI插件实现对Excel的操作(导入,导出,合并单元格,设置样式,输入公式)

    前言 NPOI 是 POI 项目的.NET版本,它不使用 Office COM 组件,不需要安装 Microsoft Office,目前支持 Office 2003 和 2007 版本. 1.整个Ex ...

  8. java 中Excel的导入导出

    部分转发原作者https://www.cnblogs.com/qdhxhz/p/8137282.html雨点的名字  的内容 java代码中的导入导出 首先在d盘创建一个xlsx文件,然后再进行一系列 ...

  9. asp.net Mvc Npoi 导出导入 excel

    因近期项目遇到所以记录一下: 首先导出Excel : 首先引用NPOI包 http://pan.baidu.com/s/1i3Fosux (Action一定要用FileResult) /// < ...

随机推荐

  1. node、Mongo项目如何前后端分离提供接口给前端

    node接口编写,vue-cli代理接口方法  通常前端使用的MocK 数据的方法,去模拟假的数据,但是如果有node Mongodb 去写数据的话就不需要在去mock 数据了,具体的方法如下. 首先 ...

  2. Uoj #218. 【UNR #1】火车管理 可持久化线段树+思维

    Code: #include<bits/stdc++.h> #define maxn 500005 using namespace std; int n,Q,ty,lastans=0; i ...

  3. EL截取url中参数

    function getUrlString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*) ...

  4. 11.6 【Linq】分组和延续

    11.6.1 使用 group...by 子句进行分组 class Program { static void Main(string[] args) { var query = from defec ...

  5. [luogu2319 HNOI2006] 超级英雄 (匈牙利算法)

    传送门 Description 现在电视台有一种节目叫做超级英雄,大概的流程就是每位选手到台上回答主持人的几个问题,然后根据回答问题的多少获得不同数目的奖品或奖金.主持人问题准备了若干道题目,只有当选 ...

  6. CentOS 7.2 x64 配置SVN服务器

    说明: SVN(subversion)的运行方式有两种: 一种是基于Apache的http.https网页访问形式,还有一种是基于svnserve的独立服务器模式. SVN的数据存储方式也有两种:一种 ...

  7. CentOS7安装Kubernetes

    CentOS7安装Kubernetes 安装Kubernetes时候需要一台机器作为管理机器,1台或者多台机器作为集群中的节点. 系统信息: Hosts: 请将IP地址换成自己环境的地址. cento ...

  8. 配置Master与Slave实现主从同步

    Mysql版本 通过docker启动的mysql容器 mysql版本 root@1651d1cab219:/# mysql --version mysql Ver 14.14 Distrib 5.6. ...

  9. Python语言数据结构和语言结构(2)

    目录 1. Python预备基础 2. Python数据类型 3. Python条件语句 4. while循环和for循环 1. Python预备基础 1.1 变量的命名   变量命名规则主要有以下几 ...

  10. Unity 利用FFmpeg实现录屏、直播推流、音频视频格式转换、剪裁等功能

    目录 一.FFmpeg简介. 二.FFmpeg常用参数及命令. 三.FFmpeg在Unity 3D中的使用. 1.FFmpeg 录屏. 2.FFmpeg 推流. 3.FFmpeg 其他功能简述. 一. ...