文章由于写得比较仓促

已经重写,源码和文章请跳转

http://www.cnblogs.com/ymnets/p/5621706.html

系列目录

前言:

导入导出实在多例子,很多成熟的组建都分装了导入和导出,这一节演示利用LinqToExcel组件对Excel的导入,这个是一个极其简单的例子。

我并不是说导入的简单。而是LinqToExcel让我们对Excel操作更加简单!

最后我们将利用ClosedXML输出Excel。这个比现流行NPOI与EPPlus更加优秀的组件,以Open XML SDK为基础,所以只支持xlsx,不支持xls格式(现阶段谁没有个office2007以上版本)

他导出的Excel根据官方描述,兼容性远超同行对手

如果你不是使用本架构只看2,3,4点,使用BLL层的代码,这同样适用你的MVC程序

知识点:

  • LinqToExcel组件读取Excel文件
  • ClosedXML组件输出Excel

准备:

  1. 一张演示的数据库表
  2. 安装LinqToExcel NuGet包
  3. 文件上传样例
  4. (时间关系只能在下一节)

开始:

1.数据表

CREATE TABLE [dbo].[Spl_Person](
[Id] [nvarchar](50) NOT NULL, --ID
[Name] [nvarchar](50) NULL, --姓名
[Sex] [nchar](10) NULL, --性别
[Age] [int] NULL, --年龄
[IDCard] [nvarchar](50) NULL, --IDCard
[Phone] [nvarchar](50) NULL, --电话
[Email] [nvarchar](200) NULL, --邮件
[Address] [nvarchar](300) NULL, --地址
[CreateTime] [datetime] NOT NULL, --创建时间
[Region] [nvarchar](50) NULL, --区域
[Category] [nvarchar](50) NULL, --类别
CONSTRAINT [PK_Spl_Person] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] GO

如何使用这个框架?

按照之前的做法,更新到EF。并利用T4生成DAL,BLL,MODEL。再用代码生成器生成界面复制进解决方案,一步到位

配置好访问地址和权限,直接运行

再手动在工具栏添加导入和导出的按钮(别忘记添加权限)

    @Html.ToolButton("btnImport", "fa fa-level-down", Resource.Import, perm, "Import", true)
@Html.ToolButton("btnExport", "fa fa-level-up", Resource.Export, perm, "Export", true)

2.安装LinqToExcel包

因为我们读取Excel放在BLL层,所有在BLL层安装LinqToExcel包

3.文件上传

(这一点简单带过,可以到网上下载上传代码植入到自己系统中)

或者下载第32节的源码 或者使用你有自己的上传文件功能

我这里使用普通的form上传功能

添加导入前端代码

<div id="uploadExcel" class="easyui-window" data-options="modal:true,closed:true,minimizable:false,shadow:false">
<form name="form1" method="post" id="form1">
<table>
<tr>
<th style=" padding:20px;">Excel:</th>
<td style=" padding:20px;">
<input name="ExcelPath" type="text" maxlength="" id="txtExcelPath" readonly="readonly" style="width:200px" class="txtInput normal left">
<a href="javascript:$('#FileUpload').trigger('click').void(0);;" class="files">@Resource.Browse</a>
<input class="displaynone" type="file" id="FileUpload" name="FileUpload" onchange="Upload('ExcelFile', 'txtExcelPath', 'FileUpload');">
<span class="uploading">@Resource.Uploading</span>
</td>
</tr>
</table>
<div class="endbtndiv">
<a id="btnSave" href="javascript:ImportData()" class="easyui-linkbutton btns">Save</a>
<a id="btnReturn" href="javascript:$('#uploadExcel').window('close')" class="easyui-linkbutton btnc">Close</a>
</div>
</form>
</div>

导入按钮事件只要弹出上传框就好

  $("#btnImport").click(function () {
$("#uploadExcel").window({ title: '@Resource.Import', width: 450, height: 160, iconCls: 'icon-details' }).window('open');
});

保证上传是成功的。

-------------------------------------------------------------------------------------------------------上面只是前期的准备工作--------------------------------------------------------------

在业务层添加以下代码

using Apps.Common;
using Apps.Models;
using Apps.Models.Spl;
using LinqToExcel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Apps.Spl.BLL
{
public partial class Spl_ProductBLL
{
/// <summary>
/// 校验Excel数据
/// </summary>
public bool CheckImportData( string fileName, List<Spl_PersonModel> personList,ref ValidationErrors errors )
{ var targetFile = new FileInfo(fileName); if (!targetFile.Exists)
{ errors.Add("导入的数据文件不存在");
return false;
} var excelFile = new ExcelQueryFactory(fileName); //对应列头
excelFile.AddMapping<Spl_PersonModel>(x => x.Name, "Name");
excelFile.AddMapping<Spl_PersonModel>(x => x.Sex, "Sex");
excelFile.AddMapping<Spl_PersonModel>(x => x.Age, "Age");
excelFile.AddMapping<Spl_PersonModel>(x => x.IDCard, "IDCard");
excelFile.AddMapping<Spl_PersonModel>(x => x.Phone, "Phone");
excelFile.AddMapping<Spl_PersonModel>(x => x.Email, "Email");
excelFile.AddMapping<Spl_PersonModel>(x => x.Address, "Address");
excelFile.AddMapping<Spl_PersonModel>(x => x.Region, "Region");
excelFile.AddMapping<Spl_PersonModel>(x => x.Category, "Category");
//SheetName
var excelContent = excelFile.Worksheet<Spl_PersonModel>(0); int rowIndex = 1; //检查数据正确性
foreach (var row in excelContent)
{
var errorMessage = new StringBuilder();
var person = new Spl_PersonModel(); person.Id =
person.Name = row.Name;
person.Sex = row.Sex;
person.Age = row.Age;
person.IDCard = row.IDCard;
person.Phone = row.Phone;
person.Email = row.Email;
person.Address = row.Address;
person.Region = row.Region;
person.Category = row.Category; if (string.IsNullOrWhiteSpace(row.Name))
{
errorMessage.Append("Name - 不能为空. ");
} if (string.IsNullOrWhiteSpace(row.IDCard))
{
errorMessage.Append("IDCard - 不能为空. ");
} //=============================================================================
if (errorMessage.Length > 0)
{
errors.Add(string.Format(
"第 {0} 列发现错误:{1}{2}",
rowIndex,
errorMessage,
"<br/>"));
}
personList.Add(person);
rowIndex += 1;
}
if (errors.Count > 0)
{
return false;
}
return true;
} /// <summary>
/// 保存数据
/// </summary>
public void SaveImportData(IEnumerable<Spl_PersonModel> personList)
{
try
{
DBContainer db = new DBContainer();
foreach (var model in personList)
{
Spl_Person entity = new Spl_Person();
entity.Id = ResultHelper.NewId;
entity.Name = model.Name;
entity.Sex = model.Sex;
entity.Age = model.Age;
entity.IDCard = model.IDCard;
entity.Phone = model.Phone;
entity.Email = model.Email;
entity.Address = model.Address;
entity.CreateTime = ResultHelper.NowTime;
entity.Region = model.Region;
entity.Category = model.Category;
db.Spl_Person.Add(entity);
}
db.SaveChanges();
}
catch (Exception ex)
{
throw;
}
}
}
}

BLL

 public class ValidationErrors : List<ValidationError>
{
/// <summary>
/// 添加错误
/// </summary>
/// <param name="errorMessage">信息描述</param>
public void Add(string errorMessage)
{
base.Add(new ValidationError { ErrorMessage = errorMessage });
}
/// <summary>
/// 获取错误集合
/// </summary>
public string Error
{
get {
string error = "";
this.All(a => {
error += a.ErrorMessage;
return true;
});
return error;
}
}
}

ValidationError

代码包含两个方法

public bool CheckImportData( string fileName, List<Spl_PersonModel> personList,ValidationErrors errors )

fileName为我们上传的文件。

personList为承接数据List

ValidationErrors 错误集合

public void SaveImportData(IEnumerable<Spl_PersonModel> personList)

保存数据

别忘记添加接口

   public partial interface ISpl_PersonBLL
{
bool CheckImportData(string fileName, List<Spl_PersonModel> personList, ref ValidationErrors errors);
void SaveImportData(IEnumerable<Spl_PersonModel> personList);
}

简单明白,直接看代码,不再解析。OK这样控制器就可以直接调用了

  public ActionResult Import(string filePath)
{
var personList = new List<Spl_PersonModel>();
//校验数据is
bool checkResult = m_BLL.CheckImportData(filePath, personList, ref errors);
//校验通过直接保存
if (checkResult)
{
m_BLL.SaveImportData(personList);
LogHandler.WriteServiceLog(GetUserId(),"导入成功", "成功", "导入", "Spl_Person");
return Json(JsonHandler.CreateMessage(, Resource.InsertSucceed));
}
else
{
string ErrorCol = errors.Error;
LogHandler.WriteServiceLog(GetUserId(), ErrorCol, "失败", "导入", "Spl_Person");
return Json(JsonHandler.CreateMessage(, Resource.InsertFail + ErrorCol));
} }

最后前端还需要把路径给回来。

 function ImportData()
{
$.post("@Url.Action("Import")?filePath=" + $("#txtExcelPath").val(), function (data) {
if (data.type == ) {
$("#List").datagrid('load');
$('#uploadExcel').window('close');
}
$.messageBox5s('@Resource.Tip', data.message); }, "json");
}

OK测试一下!建立一个新的excel格式

一般情况下我们是提供模版给用户下载供用户输入数据,来确保格式的正确性

总结:

虽然做好了导出功能,但是来不及发代码。只能到下次有时间再分析导出功能

本节知识点,全部聚集在CheckImportData方法上。

对应列头是模版xlsx的列头

1.如果模版需要是是中文的,如Name=名字,那么方法应该这么写

excelFile.AddMapping<Spl_PersonModel>(x => x.Name, "名字");

2.导入第几个sheet工作薄可以这么写

我这里写0是指第一个sheet工作薄。可以直接指定工作薄

var excelContent = excelFile.Worksheet<Spl_PersonModel>("Sheet1");

3.检查正确性可以确保数据的来源。可以给出用户正确的修改提示。

已经重写,源码和文章请跳转http://www.cnblogs.com/ymnets/p/5621706.html的更多相关文章

  1. [Abp vNext 源码分析] - 文章目录

    一.简要介绍 ABP vNext 是 ABP 框架作者所发起的新项目,截止目前 (2019 年 2 月 18 日) 已经拥有 1400 多个 Star,最新版本号为 v 0.16.0 ,但还属于预览版 ...

  2. 精尽Spring Boot源码分析 - 文章导读

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  3. 精尽MyBatis源码分析 - 文章导读

    该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...

  4. 精尽Spring MVC源码分析 - 文章导读

    该系列文档是本人在学习 Spring MVC 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释 Spring MVC 源码分析 GitHub 地址 进行阅读 Spring 版本:5.2. ...

  5. Dubbo源码学习文章目录

    目录 Dubbo源码学习--服务是如何发布的 Dubbo源码学习--服务是如何引用的 Dubbo源码学习--注册中心分析 Dubbo源码学习--集群负载均衡算法的实现

  6. winrt 上的翻书特效组件 源码分享 转载请说明

    http://blog.csdn.net/wangrenzhu2011/article/details/10207413 (转) [TemplatePart(Name = A_PARTNAME, Ty ...

  7. [微信跳转浏览器]微信跳转外部浏览器下载APP源码,可以实现自动跳转外部浏览器打开链接

    基于微信后端开发了一款微信推广助手,使用了本程序生成的链接,用户在微信任意环境下点击链接或者扫描二维码,可以实现直接跳转手机默认浏览器并打开指定网页. 我们开发的此款跳转产品,应用范围广泛.除了下载A ...

  8. 读logback源码系列文章(五)——Appender --转载

    原文地址:http://kyfxbl.iteye.com/blog/1173788 明天要带老婆出国旅游几天,所以这段时间暂时都更新不了博客了,临走前再最后发一贴 上一篇我们说到Logger类的inf ...

  9. cocos creator 重写源码按钮Button点击音频封装

    (function(){ var Super = function(){}; Super.prototype = cc.Button.prototype; //实例化原型 Super.prototyp ...

随机推荐

  1. 纯CSS3实现的一些酷炫效果

    之前在网上看到一些用纯CSS3实现的酷炫效果,以为实现起来比较困难,于是想看看具体是怎么实现的. 一.笑脸猫动画 实现效果如下: 这个实现起来确实比较麻烦,很多地方需要花时间,有耐心地调整. 1.先看 ...

  2. Taurus.MVC 2.0 开源发布:WebAPI开发教程

    背景: 有用户反映,Tausus.MVC 能写WebAPI么? 能! 教程呢? 嗯,木有! 好吧,刚好2.0出来,就带上WEBAPI教程了! 开源地址: https://github.com/cyq1 ...

  3. 我是如何在SQLServer中处理每天四亿三千万记录的

    首先声明,我只是个程序员,不是专业的DBA,以下这篇文章是从一个问题的解决过程去写的,而不是一开始就给大家一个正确的结果,如果文中有不对的地方,请各位数据库大牛给予指正,以便我能够更好的处理此次业务. ...

  4. SQL Server内存遭遇操作系统进程压榨案例

    场景: 最近一台DB服务器偶尔出现CPU报警,我的邮件报警阈(请读yù)值设置的是15%,开始时没当回事,以为是有什么统计类的查询,后来越来越频繁. 探索: 我决定来查一下,究竟是什么在作怪,我排查的 ...

  5. ABP教程-打造一个《电话簿项目》-目录-MPA版本-基于ABP1.13版本

    此系列文章会进行不定期的更新,应该会有6章左右. 感兴趣的朋友可以跟着看看,本教程适合已经看过ABP的文档但是又无从下手的小伙伴们. 初衷: 发布系列教程的原因是发现ABP在园子火了很久,但是发现还是 ...

  6. 在Linux虚拟机下配置tomcat

    1.到Apache官网下载tomcat http://tomcat.apache.org/download-80.cgi 博主我下载的是tomcat8 博主的jdk是1.8 如果你们的jdk是1.7或 ...

  7. 【开源】分享2011-2015年全国城市历史天气数据库【Sqlite+C#访问程序】

    由于个人研究需要,需要采集天气历史数据,前一篇文章:C#+HtmlAgilityPack+XPath带你采集数据(以采集天气数据为例子),介绍了基本的采集思路和核心代码,经过1个星期的采集,历史数据库 ...

  8. 学习ASP.NET Core,怎能不了解请求处理管道[2]: 服务器在管道中的“龙头”地位

    ASP.NET Core管道由注册的服务器和一系列中间件构成.我们在上一篇中深入剖析了中间件,现在我们来了解一下服务器.服务器是ASP .NET Core管道的第一个节点,它负责完整请求的监听和接收, ...

  9. 【原创分享·微信支付】C# MVC 微信支付教程系列之现金红包

            微信支付教程系列之现金红包           最近最弄这个微信支付的功能,然后扫码.公众号支付,这些都做了,闲着无聊,就看了看微信支付的其他功能,发现还有一个叫“现金红包”的玩意,想 ...

  10. iOS开发之ReactiveCocoa下的MVVM(干货分享)

    最近工作比较忙,但还是出来更新博客了,今天给大家分享一些ReactiveCocoa以及MVVM的一些东西,干活还是比较足的.在之前发表过一篇博文,名字叫做<iOS开发之浅谈MVVM的架构设计与团 ...