ASP.NET MVC 导入Excel文件(完整版)
View视图部分:
<form method="post" enctype="multipart/form-data" action="/Position/ImportExcel" class="form-group">
<input name="file" type="file" id="file" />
<button id="btn_import" type="submit" class="btn btn-info">
<span class="glyphicon glyphicon-pencil"></span>导入
</button>
</form>
控制器部分:
public ActionResult ImportExcel()
{
//获取上传的Excel文件
HttpPostedFileBase File = Request.Files["file"];
string message = "";
if (File.ContentLength > 0)
{
//GetExtension:返回指定路径的文件的扩展名
var Isxls = System.IO.Path.GetExtension(File.FileName).ToString().ToLower();
if (Isxls != ".xls" && Isxls != ".xlsx")
{
message = "<script>alert('请上传Excel文件'),window.location.href='/Position/Index'</script>";
}
var FileName = File.FileName;//获取文件夹名称
var path = Server.MapPath("~/FileExcel/" + FileName);
File.SaveAs(path);//将文件保存到服务器
PositionBLL bll = new PositionBLL();
var list = bll.FileUpLoad(path);
if (list.Count > 0)
{
int num = bll.LoadFile(list);
if (num > 0)
{
message = "<script>alert('数据导入成功'),window.location.href='/Position/Index'</script>";
}
}
else
{
message = "<script>alert('导入的数据不能为空'),window.location.href='/Position/Index'</script>";
}
}
else
{
message = "<script>alert('请选择上传的文件'),window.location.href='/Position/Index'</script>";
}
return Content(message);
}
Model部分:
public class PositionModel
{
string PositionName;
string Qualification;
string Remark;
public string PositionName1 { get => PositionName; set => PositionName = value; }
public string Qualification1 { get => Qualification; set => Qualification = value; }
public string Remark1 { get => Remark; set => Remark = value; }
}
PositionBLL部分:
public class PositionBLL
{
//private const string ConnString2003 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0';HDR='Yes'";
//链接打开excel的字符串
private const string ConnString2003 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0';";
public List<PositionModel> FileUpLoad(string filePath)
{
DataSet ds = new DataSet();
List<PositionModel> list = new List<PositionModel>();
string strSQL = string.Format(ConnString2003, filePath);
//OleDbConnection:表示与数据源的开放链接
OleDbConnection conn = new OleDbConnection(strSQL);
try
{
//判断连接的状态
if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
{
conn.Open();
}
DataTable tableName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//获取Excel的第一个Sheet名称
var sheetName = tableName.Rows[0]["TABLE_NAME"].ToString().Trim();
string SQL = "select * from [" + sheetName + "]";
OleDbDataAdapter sa = new OleDbDataAdapter(SQL, conn);
sa.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
PositionModel model = new PositionModel();
model.PositionName1 = dr["职位名称"].ToString();
model.Qualification1 = dr["任职资格"].ToString();
model.Remark1 = dr["职位描述"].ToString();
list.Add(model);
}
}
catch (Exception ex)
{
Console.WriteLine("错误信息:PositionBLL+FileUpLoad方法" + ex);
}
return list;
}
//将数据循环遍历到数据库中
PositionDAL dal = new PositionDAL();
public int LoadFile(List<PositionModel> list)
{
var num = 0;
foreach (var item in list)
{
PositionModel model = new PositionModel();
model.PositionName1 = item.PositionName1;
model.Qualification1 = item.Qualification1;
model.Remark1 = item.Remark1;
num = dal.Add(model);
}
return num;
}
PositionDAL部分:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ExcleImport.Models
{
public class PositionDAL
{
DBhelper dBhelper = new DBhelper();
public int Add(PositionModel model) {
string sql = string.Format("insert into userInfo (position,grade,remark)values('{0}','{1}','{2}')", model.PositionName1, model.Qualification1, model.Remark1);
return dBhelper.ExceDml(sql);
}
}
}
DBhelper部分:
//创建链接数据库的字符串
string dbStr = "Data Source=.;Initial Catalog=sales;Integrated Security=True";
public int ExceDml(string sql)
{
try
{
int res = 0;
//连接数据库
using (SqlConnection conn = new SqlConnection(dbStr))
{
//打开连接数据库
conn.Open();
//执行sql
SqlCommand comm = new SqlCommand(sql, conn);
res = comm.ExecuteNonQuery();
}
return res;
}
catch (Exception ex)
{
Console.WriteLine("错误信息:DBhelper+ExceDml方法" + ex);
throw ex;
}
}
数据库表:
create table userInfo
(
id int identity(1,1)not null,
position varchar(50)not null,
grade varchar(50)not null,
remark varchar(100)not null
)
ASP.NET MVC 导入Excel文件(完整版)的更多相关文章
- ASP.NET MVC 导入Excel文件
一:view部分 <form method="post" enctype="multipart/form-data" action="/Posi ...
- ASP.NET MVC导入excel到数据库
MVC导入excel和webform其实没多大区别,以下为代码: 视图StationImport.cshtml的代码: @{ ViewBag.Title = "StationImport&q ...
- ASP.NET MVC实现Excel文件的上传下载
在应用系统开发当中,文件的上传和下载是非常普遍的需求.在基于.NET的C/S架构的项目开发当中,有多种方案可以实现文件的上传和下载(httpwebrequest.webclient等),而且多采用异步 ...
- JavaScript日历控件开发 C# 读取 appconfig文件配置数据库连接字符串,和配置文件 List<T>.ForEach 调用异步方法的意外 ef 增加或者更新的习惯思维 asp.net core导入excel 一个二级联动
JavaScript日历控件开发 概述 在开篇之前,先附上日历的代码地址和演示地址,代码是本文要分析的代码,演示效果是本文要实现的效果代码地址:https://github.com/aspwebc ...
- .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)
.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构) public cl ...
- ASP.NET MVC导出excel
ASP.NET MVC导出excel 要在ASP.NET MVC站点上做excel导出功能,但是要导出的excel文件比较大,有几十M,所以导出比较费时,为了不影响对界面的其它操作,我就采用异步的方式 ...
- springMVC(5)---导入excel文件数据到数据库
springMVC(5)---导入excel文件数据到数据库 上一篇文章写了从数据库导出数据到excel文件,这篇文章悄悄相反,写的是导入excel文件数据到数据库.上一篇链接:springMVC(4 ...
- 利用kettle组件导入excel文件到数据库
利用kettle组件导入excel文件到数据库 1. 实现目标 把excel文件内容导入到目标表中:然后用java调用kettle的转换.excel文件的内容仅仅有两列,示比例如以下: wat ...
- Asp.Net Core 导入Excel数据到Sqlite数据库并重新导出到Excel
Asp.Net Core 导入Excel数据到Sqlite数据库并重新导出到Excel 在博文"在Asp.Net Core 使用 Sqlite 数据库"中创建了ASP.NET Co ...
随机推荐
- AI剪辑和自定义UI,打造更智能的剪辑体验
为满足开发者构建高效的应用内视频编辑能力,7月的HMS Core 6.0 推出了视频编辑服务(Video Editor Kit),一站式的视频处理能力获得了积极反响.同时,我们也关注到开发者需要集成丰 ...
- 进击的 Ansible(二):如何快速搞定生产环境 Ansible 项目布局?
Tips:与前文 <进击的 Ansible(一):Ansible 快速入门> 一样,本文使用的 Ansible 版本 2.5.4,项目演示环境 MacOS.由于 Ansible 项目开发活 ...
- [R]在dplyr函数的基础上编写函数-(3)tidyeval
dplyr的优点很明显,数据框操作简洁,如filter(df, x == 1, y == 2, z == 3)等于df[df$x == 1 & df$y ==2 & df$z == 3 ...
- Linux Alpine安装 Nginx
Linux Alpine安装 Nginx 安装需要编译Nginx的扩展 apk add wget gcc g++ make 安装Nginx URL重定向,正则表达式模块pcre Pcre 源码下载地址 ...
- C# CheckBoxList-DropDownList回显、筛选回显
<asp:CheckBoxList ID="ddlType" runat="server" RepeatColumns="10" Re ...
- day06 视图层
day06 视图层 今日内容 视图层 小白必会三板斧 JsonResponse form表单发送文件 FBV与CBV FBV基于函数的视图 CBV基于类的视图 模板层 模板语法的传值 模板语法之过滤器 ...
- day13 iptables防火墙
day13 iptables防火墙 一.防火墙的概述 1.什么是防火墙 防止恶意流量访问的软件就叫做防火墙. 2.防火墙的种类 软件防火墙:firewalld.iptables 硬件防火墙:F5 fi ...
- Spark的shuffle和MapReduce的shuffle对比
目录 MapperReduce的shuffle Spark的shuffle 总结 MapperReduce的shuffle shuffle阶段划分 Map阶段和Reduce阶段 任务 MapTask和 ...
- Scala(三)【函数式编程】
目录 一.方法和函数 1.方法 1)基本语法 2)简化原则 3)方法参数 2.函数 3.方法和函数的区别 二.高阶函数 三.匿名函数 四.柯里化 五.闭包 一.方法和函数 1.方法 1)基本语法 de ...
- 关于form表单提交ajaxForm和ajaxSubmit的用法与区别
前几天在学习form表单提交时看到这两种方法,这两种方法都是实现form的ajax提交的方法,看了很多资料还是不太明白其用法和区别,最后直接自己写demo,很快就理解,所以说实操是学习的最快捷直接的途 ...