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. fiddler抓包 IOS11以上系统

    想要使用fiddler对iphone X进行抓包,按照以前的配置方法,走一遍.还是抓不成,原来是因为IOS11操作系统中,安装完证书之后,还需要再手动信任证书才能正常抓包. 以下内容来自:https: ...

  2. 【双系统】windows 和 Ubuntu 双系统安装

      本博客主要讲述如何在已安装windows系统的计算机上安装Ubuntu双系统,涉及系统安装和相应磁盘空间分配等问题. 所需环境: 电脑已安装windows系统 下载Ubuntu16.04系统镜像 ...

  3. greenplum数据迁移

    源集群: 登录集群su - gpadminpsql -d postgres查询数据库信息\l查询用户信息\du 备份需要迁移的库到指定目录pg_dump -C testdata > /home/ ...

  4. vue 手机键盘把底部按钮顶上去

    背景:在写提交订单页面时候,底部按钮当我点击输入留言信息的时候,底部提交订单按钮被输入法软键盘顶上去遮挡住了. h5 ios输入框与键盘 兼容性优化 实现原理:当页面高度发生变化的时候改变底部butt ...

  5. 继续聊WPF

    下面看一个Tick控件的例子,这只是演示,Tick单独使用没有意义. <TickBar Height="15" Width="180" Ticks=&qu ...

  6. SOA案例架构分析浅谈

    上课中讲到了SOA架构设计,自己在课下决定总结一下对于SOA架构的理解以及应用. 先总结一下SOA的定义,SOA是面向服务架构,它可以根据需求通过网络对松散耦合的粗粒度应用组件进行分布式部署.组合和使 ...

  7. 【codeforces 798A】Mike and palindrome

    [题目链接]:http://codeforces.com/contest/798/problem/A [题意] 让你严格改变一个字符,使得改变后的字符串为一个回文串; 让你输出可不可能; [题解] 直 ...

  8. IE-FSC

    Top3: Top2: FSC related to Redis: (Redis = https://www.cnblogs.com/ngtest/p/10693750.html) FSC statu ...

  9. 0929误删除innodb ibdata数据文件

    今天在群里看到有人说不熟悉innodb把ibdata(数据文件)和ib_logfile(事务日志)文件误删除了.不知道怎么解决.当时我也不知道怎么办.后来查阅相关资料.终找到解决方法.其实恢复也挺简单 ...

  10. 淘宝内部分享:MySQL & MariaDB性能优化

    发表于2015-01-20 16:26| 28875次阅读| 来源mysql.taobao.org| 22 条评论| 作者淘宝数据库团队 MySQL性能优化淘宝数据库 摘要:MySQL是目前使用最多的 ...