MVC导入excel和webform其实没多大区别,以下为代码:

视图StationImport.cshtml的代码:

@{
ViewBag.Title = "StationImport";
Layout = "~/Areas/Admin/Views/Shared/_index.cshtml";
}
@using (Html.BeginForm("StationImport", "Station", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<h2>
基站信息导入</h2>
<div>
<fieldset id="myfieldset">
<legend>excel模版格式 </legend><font color="red">导入基站的模板格式如下,若模板格式不正确,则相应的基站不能导入!</font><br />
<img src="http://www.cnblogs.com/http://www.cnblogs.com/Content/AdminImages/stationexceltemplate.png" />
<p style="color: Red; text-align: center;">@Html.ActionLink("下载模版", "GetFile")</p>
</fieldset>
</div>
<div style="margin-top: 20px;">
<fieldset id="myfieldset1">
<legend>基站批量信息导入</legend>
<p>
选择文件:<input id="FileUpload" type="file" name="files" style="width: 250px; height: 24px;
background: White" class="easyui-validatebox" /></p>
<p>
<input id="btnImport" type="submit" value="导入" style="width: 60px; height: 28px;" /></p>
<p style="color: Red; text-align: center;">@ViewBag.error</p>
</fieldset>
</div>
}

控制器相关方法的代码:使用TransactionScope类以确保存储数据全部都成功执行才算完成。如果要使用TransactionScope类,必须在项目中添加System.Transaction组件。

  #region 批量导入基站
public ActionResult StationImport()
{
return View();
}
[HttpPost]
public ActionResult StationImport(HttpPostedFileBase filebase)
{
HttpPostedFileBase file=Request.Files["files"];
string FileName;
string savePath;
if (file == null||file.ContentLength<=0)
{
ViewBag.error = "文件不能为空";
return View();
}
else
{
string filename= Path.GetFileName(file.FileName);
int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
string fileEx = System.IO.Path.GetExtension(filename);//获取上传文件的扩展名
string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
string FileType = ".xls,.xlsx";//定义上传文件的类型字符串 FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
if (!FileType.Contains(fileEx))
{
ViewBag.error = "文件类型不对,只能导入xls和xlsx格式的文件";
return View();
}
if (filesize >= Maxsize)
{
ViewBag.error = "上传文件超过4M,不能上传";
return View();
}
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/excel/";
savePath = Path.Combine(path, FileName);
file.SaveAs(savePath);
} //string result = string.Empty;
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +savePath+ ";" + "Extended Properties=Excel 8.0";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", strConn);
DataSet myDataSet = new DataSet();
try
{
myCommand.Fill(myDataSet, "ExcelInfo");
}
catch (Exception ex)
{
ViewBag.error = ex.Message;
return View();
}
DataTable table = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable(); //引用事务机制,出错时,事物回滚
using (TransactionScope transaction = new TransactionScope())
{
for (int i = 0; i < table.Rows.Count; i++)
{
//获取地区名称
string _areaName = table.Rows[i][0].ToString();
//判断地区是否存在
if (!_areaRepository.CheckAreaExist(_areaName))
{
ViewBag.error = "导入的文件中:" + _areaName + "地区不存在,请先添加该地区";
return View();
}
else
{
Station station = new Station();
station.AreaID = _areaRepository.GetIdByAreaName(_areaName).AreaID;
station.StationName = table.Rows[i][1].ToString();
station.TerminaAddress = table.Rows[i][2].ToString();
station.CapacityGrade = table.Rows[i][3].ToString();
station.OilEngineCapacity = decimal.Parse(table.Rows[i][4].ToString());
_stationRepository.AddStation(station);
}
}
transaction.Complete();
}
ViewBag.error = "导入成功";
System.Threading.Thread.Sleep(2000);
return RedirectToAction("Index");
}
#endregion

文件下载,FileResult类可以响应任意的文件内容,包括二进制格式的数据,在ASP.NET MVC中实现FileResult类的子类共有3个,分别是

1、FilePathResult:响应一个实体文件

2、FileContentResult:响应一个byte数组的内容

3、FileStreamResult:响应一个Stream数据

FilePathResult和FileStreamResult的区别是什么?我们又该如何取舍呢?主要的区别是FilePathResult使用HttpResponse.TransmitFile来将文件写入Http输出流。这个方法并不会在服务器内存中进行缓冲,所以这对于发送大文件是一个不错的选择。他们的区别很像DataReader和DataSet的区别。于此同时, TransmitFile还有一个bug,这可能导致文件传到客户端一半就停了,甚至无法传送。而FileStreamResult在这方面就很棒了。比如说:返回Asp.net Chart 控件在内存中生成的图表图片,而这并不需要将图片存到磁盘中.

File()辅助方法能自动选取不同的FileResult类进行。

以下为文件下载的代码:

      public FileResult GetFile()
{
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/excel/";
string fileName = "基站信息Excel模版.xls";
return File(path + fileName, "text/plain", fileName);
}

ASP.NET MVC导入excel到数据库的更多相关文章

  1. ASP.NET MVC 导入Excel文件(完整版)

    View视图部分: <form method="post" enctype="multipart/form-data" action="/Pos ...

  2. ASP.NET MVC 导入Excel文件

    一:view部分 <form method="post" enctype="multipart/form-data" action="/Posi ...

  3. Asp.Net Core 导入Excel数据到Sqlite数据库并重新导出到Excel

    Asp.Net Core 导入Excel数据到Sqlite数据库并重新导出到Excel 在博文"在Asp.Net Core 使用 Sqlite 数据库"中创建了ASP.NET Co ...

  4. JavaScript日历控件开发 C# 读取 appconfig文件配置数据库连接字符串,和配置文件 List<T>.ForEach 调用异步方法的意外 ef 增加或者更新的习惯思维 asp.net core导入excel 一个二级联动

    JavaScript日历控件开发   概述 在开篇之前,先附上日历的代码地址和演示地址,代码是本文要分析的代码,演示效果是本文要实现的效果代码地址:https://github.com/aspwebc ...

  5. 一步步实现ABAP后台导入EXCEL到数据库【3】

    在一步步实现ABAP后台导入EXCEL到数据库[2]里,我们已经实现计划后台作业将数据导入数据库的功能.但是,这只是针对一个简单的自定义结构的导入程序.在实践应用中,面对不同的表.不同的导入文件,我们 ...

  6. 一步步实现ABAP后台导入EXCEL到数据库【1】

    在SAP的应用当中,导入.导出EXCEL文件的情况是一个常见的需求,有时候用户需要将大量数据定期导入到SAP的数据库中.这种情况下,使用导入程序在前台导入可能要花费不少的时间,如果能安排导入程序为后台 ...

  7. 【第一篇】ASP.NET MVC快速入门之数据库操作(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

  8. 如何使用NPOI 导出到excel和导入excel到数据库

    近期一直在做如何将数据库的数据导出到excel和导入excel到数据库. 首先进入官网进行下载NPOI插件(http://npoi.codeplex.com/). 我用的NPOI1.2.5稳定版. 使 ...

  9. ASP.NET MVC导出excel

    ASP.NET MVC导出excel 要在ASP.NET MVC站点上做excel导出功能,但是要导出的excel文件比较大,有几十M,所以导出比较费时,为了不影响对界面的其它操作,我就采用异步的方式 ...

随机推荐

  1. SQL Server 的三种用户自定义函数

    create function fun_A()   #标题函数.create function fun_name() returns output_type as begin return value ...

  2. 要不要用STL的问题——真理是越辩越明的~

    QtWidgets的维护者 Marc Mutz 有一篇博客比较详尽的介绍了 Qt自己的容器.介绍了何时用什么比较好https://marcmutz.wordpress.com/effective-qt ...

  3. Day3_字符串操作与正则表达式

    本节课的主要内容有:字符串的格式化.连接与分割.比较.匹配和替换.使用正则表达式 字符串的格式化: 去除空格:trim() 使用html格式化:nl2br()  替换‘\n’为‘<br /> ...

  4. jstack命令使用

    概述 jstack可用于导出java运用程序的线程堆栈.其基本使用语法为: jstack [-l] pid -l 选项用于打印锁的额外信息. 使用演示样例 以下这段代码执行之后会出现死锁现象(由于线程 ...

  5. c++ 回调类成员函数实现

    实现类成员函数的回调,并非静态函数:区分之 #ifndef __CALLBACK_PROXY_H_ #define __CALLBACK_PROXY_H_ template <typename ...

  6. Unity3D-第一视角射击游戏

    一.新建关卡 File,Save Scene,File,New Scene,File,Save Scene as... ,Level02.unity 1.建立场景 从Assets中拖放场景模型到Hie ...

  7. 【原创】重绘winform的GroupBox

    功能:重绘winform的GroupBox,以便调整边框颜色和边框宽度 using System; using System.Collections.Generic; using System.Com ...

  8. ubuntu菜单面板丢了怎么找回

    我的ubuntu菜单面板丢了.   我的ubuntu用的是gnome桌面环境,桌面环境分为三个区域: 1.菜单面板 (1)三个主菜单:应用程序,位置,系统. (2)快速启动区:菜单面板中间的部分称为快 ...

  9. UVa 116 Unidirectional TSP (DP)

    该题是<算法竞赛入门经典(第二版)>的一道例题,难度不算大.我先在没看题解的情况下自己做了一遍,虽然最终通过了,思路与书上的也一样.但比书上的代码复杂了很多,可见自己对问题的处理还是有所欠 ...

  10. Java学习之网络编程

    转自:http://blog.csdn.net/driverking/article/details/6573992 一.网络编程基本概念 1.OSI与TCP/IP体系模型 2.IP和端口 解决了文章 ...