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. 【sqli-labs】 less34 POST- Bypass AddSlashes (POST型绕过addslashes() 函数的宽字节注入)

    还是宽字节注入,POST版本的 uname=1&passwd=1%df' union select 1,2,3# 提交报错 列名不匹配,改一下就好了 uname=1&passwd=1% ...

  2. kvm之 virt-install工具命令详解

    一.virt-install是一个命令行工具,它能够为KVM.Xen或其它支持libvrit API的hypervisor创建虚拟机并完成GuestOS安装:此外,它能够基于串行控制台.VNC或SDL ...

  3. 11.6 【Linq】分组和延续

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

  4. CSS模块化思想-----命名是个技术活

    CSS模块化思想(一)--------命名是个技术活 引子: 女孩子都喜欢买衣服,而我也不例外,奈何钱包太瘦,买不起高大上的定制,只能买撞衫率极高的休闲衣,不过对于我来说,我还是开心的,毕竟买衣服买的 ...

  5. Deepin & ROMS 安装详细流程

    按照这个过程,完美安装,当然并不能排除会出现其他的问题.如果遇到了,那就老老实实上网搜吧.

  6. PHP判读MySQL是否执行成功

    针对update 语句等会对数据表进行修改的语句 在mysql_query($sql);后面加上 $result = mysql_affected_rows(); 如果$result 值为-1表明语句 ...

  7. 1069. The Black Hole of Numbers

    For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in ...

  8. cogs 983. [NOIP2003] 数字游戏

    983. [NOIP2003] 数字游戏 ★☆   输入文件:numgame.in   输出文件:numgame.out   简单对比时间限制:1 s   内存限制:128 MB 题目描述 丁丁最近沉 ...

  9. 《简明 Python 教程》笔记

    基础 字符串:python 中字符串可以用单引号.双引号和三个引号括起来,其中三个引号可以用来指定多行的字符串. print('hello'* 3) 连续打印 3 个 hello 格式化:print ...

  10. hdu - 4920 - Matrix multiplication(缓存优化+开挂)

    题意:求两个n x n的矩阵相乘后模3的结果,n <= 800. 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4920 -->>呀呀 ...