NPOI导出
// string filename = fileNameTitle + DateTime.Now.ToString("yyMMddhhmmss") + new Random().Next(100, 999);
<body>
@using (Html.BeginForm("ImportCommentsFile", "CommentsManage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="rowButton">
<input type="file" id="fileUpload" name="files" style="cursor:pointer"/>
<a style="width: 40px;color: #f00;font-size: 12px; cursor: pointer;display:none" id="clearFile">×清除</a>
<input type="submit" value="立即导入" style="cursor:pointer"/>
<p style="color: #f00; width: 140px; font-size: 12px; float: right;margin-top:5px">*EXCEL模板【<a href="@Url.Action("GetFile", "CommentsManage")">下载</a>】</p>
</div>
if (result != null)
{
<p style="color: @(result.DoFlag ? "#" : "#f00");font-family: 微软雅黑, Comic Sans MS ">
@result.DoResult
</p>
}
if(ViewBag.ErrorMsgs != null)
{
foreach (var item in ViewBag.ErrorMsgs)
{
<p style="color:#f00;font-family: 微软雅黑, Comic Sans MS">@item</p>
}
}
}
</body>
<script type="text/javascript">
//清除选择文件
$("#clearFile").click(function() {
$("#fileUpload").val("");
$(this).css("display", "none");
});
//显示清除按钮
$("#fileUpload").change(function () {
debugger;
var filename = $("#fileUpload").val();
if (filename.length > ) {
if ($("#clearFile").css("display") === "none") {
$("#clearFile").css("display", "inline-block");
}
} else {
if ($("#clearFile").css("display") === "inline-block") {
$("#clearFile").css("display", "none");
}
}
});
</script>
//Excel导入视图页
public ActionResult ImportCommnets()
{
return View();
} //Excel导入模板下载
public FileResult GetFile()
{
const string url = "~/TempExcel/商品评论模板.xls";
var fileName = Server.MapPath(url);
var name = Path.GetFileName(fileName);
return File(fileName, "application/ms-excel", Url.Encode(name));
} /// <summary>
/// 导入Excel
/// </summary>
/// <returns></returns>
public ActionResult ImportCommentsFile()
{
var ptcp = new BaseResponse { DoFlag = true, DoResult = "" };
try
{
FileUploader uploader = new FileUploader("~/Upload");
uploader.SetExtensionLimit(".xls|.xlsx");
string error;
List<string> filenames=uploader.Process(this.Request, out error);
string fileName = filenames.FirstOrDefault();
if (!string.IsNullOrEmpty(error))
{
ptcp.DoFlag = false;
ptcp.DoResult = error;
}
else
{
fileName = Path.GetFileName(fileName);
string fullPath = Path.Combine(Server.MapPath("~/Upload"), fileName);
//将excel数据导入到列表中
ImportExcelToList import = new ImportExcelToList();
MessageList errors = new MessageList();
//获取表数据
ImportToListResult importedResult = import.DoImport(fullPath);
if (importedResult.Result.IsSuccess)
{
//获取验证返回的错误信息
errors.Merge(DoValidData(importedResult.Data.ImportedBody));
if (errors.Messages != null && errors.Messages.Any())
{
ptcp.DoFlag = false;
ViewBag.ErrorMsgs = errors.Messages.Select(s => s.Message).ToList();
}
else
{
//执行导入
Stopwatch during = new Stopwatch();
during.Start();
int success = DoImport(importedResult.Data.ImportedHeader, importedResult.Data.ImportedBody);
during.Stop();
string info = success>?string.Format("导入成功!一共导入:{0}条记录,耗时{1}秒", success, during.Elapsed.TotalSeconds):"导入错误;插入失败";
ptcp.DoFlag = success > ;
ptcp.DoResult = info;
} }
else
{
ptcp.DoFlag = false;
ptcp.DoResult = importedResult.Result.Error; }
}
}
catch (Exception ex)
{
ptcp.DoFlag = false;
ptcp.DoResult = "导入异常";
} ViewBag.Result = ptcp;
return View("ImportCommnets");
} /// <summary>
/// 校验导入Excel表中数据有效性
/// </summary>
/// <param name="bodyData">表数据</param>
/// <returns></returns>
private MessageList DoValidData(List<List<object>> bodyData)
{
MessageList rtn = new MessageList();
for (int i = ; i < bodyData.Count; i++)
{
int no = i + ;
var one = bodyData[i];
//校验商品id为int且不为空
if (one[] != null)
{
int productid = ;
bool tointproductid = int.TryParse(one[].ToString(),out productid);
if (tointproductid == false)
{
rtn.Add(string.Format("第{0}行:填写的商品id不是数字", no));
continue;
}
}
else
{
rtn.Add(string.Format("第{0}行:商品id未填写", no));
continue;
}
//校验评分等级为1到5的数字且非空
if (one[] != null)
{
int score = ;
bool tointscore = int.TryParse(one[].ToString(), out score);
if (tointscore == false)
{
rtn.Add(string.Format("第{0}行:填写的商品评分不是数字", no));
continue;
}
if (score < || score > )
{
rtn.Add(string.Format("第{0}行:填写的商品评分等级数字不在1到5范围内", no));
continue;
}
}
else
{
rtn.Add(string.Format("第{0}行:商品评分等级未填写", no));
continue;
}
//如果填写手机号,校验手机号格式
if (!string.IsNullOrEmpty(one[].ToString()))
{
//^[1][358][0-9]{9}$现在只有13、15和18开头的11位手机号码。以1开头,第2位数字为3或5或8,后面接9位数字。
if (!Regex.IsMatch(one[].ToString(), @"^[1][358][0-9]{9}$"))
{
rtn.Add(string.Format("第{0}行:手机号码格式不正确", no));
continue;
}
} //如果填写邮箱,校验邮箱格式
if (!string.IsNullOrEmpty(one[].ToString()))
{
if (!Regex.IsMatch(one[].ToString(), @"^[a-z0-9]([a-z0-9\\.]*[-_]{0,4}?[a-z0-9\\.]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+([\.][\w_-]+){1,5}$"))
{
rtn.Add(string.Format("第{0}行:邮箱格式不正确", no));
continue;
}
} DateTime addtime;
bool toaddtime = DateTime.TryParse(one[].ToString(), out addtime); //评价时间
if (toaddtime == false)
{
rtn.Add(string.Format("第{0}行:评价时间不能为空", no));
continue;
} }
return rtn;
} /// <summary>
/// 执行导入
/// </summary>
/// <param name="headerDatas">表头</param>
/// <param name="bodyData">表体</param>
/// <returns></returns>
public int DoImport(List<string> headerDatas, List<List<object>> bodyData)
{
int successRec = ;
List<VipCommentProductDetail> vipcomments=new List<VipCommentProductDetail>();
foreach (var row in bodyData) //row表示一行的数据集合
{
if (row == null || row[] == null) continue; //如果Excel表中某行或某行的商品id为空就跳过 int productid = ;
bool tointproductid = int.TryParse(row[].ToString(), out productid); //商品ID string contentInfo = row[].ToString().Trim(); //评价内容 int score = ;
bool tointscore = int.TryParse(row[].ToString(), out score); //评分等级 string mobile = row[].ToString().Trim(); //用户手机 string nickname = row[].ToString().Trim(); //用户昵称 string email = row[].ToString().Trim(); //用户邮箱 DateTime addtime;
bool toaddtime = DateTime.TryParse(row[].ToString(), out addtime); //评价时间 VipCommentProductDetail commentDetail = new VipCommentProductDetail();
commentDetail.ProductId = tointproductid ? productid : ;
commentDetail.ContentInfo = contentInfo;
commentDetail.Score = tointscore ? score : ;
commentDetail.Mobile = mobile;
commentDetail.ShowNickName = nickname;
commentDetail.Email = email;
commentDetail.AddTime = addtime;
vipcomments.Add(commentDetail);
successRec++;
}
var implresult = CommentManageClient.Instance.ImportComments(vipcomments);
if (!implresult.DoFlag)
{
successRec = ;
}
return successRec;
}
<input type="submit" class="sBtn" name="action:Export" value="导出" />
/// <summary>
/// 导出
/// </summary>
/// <param name="search"></param>
/// <returns></returns>
[HttpPost]
[MultipleButton(Name = "action", Argument = "Export")]
public ActionResult Export(CommentsManageRefer search)
{
search.PageIndex = ;
search.PageSize = int.MaxValue;
//会员昵称
if (!string.IsNullOrEmpty(search.CommentDetail.ShowNickName))
{
search.CommentDetail.ShowNickName = search.CommentDetail.ShowNickName.Trim();
}
//商品
if (!string.IsNullOrEmpty(search.CommentDetail.ProductCondition))
{
search.CommentDetail.ProductCondition = search.CommentDetail.ProductCondition.Trim();
}
//评论内容
if (!string.IsNullOrEmpty(search.CommentDetail.ContentInfo))
{
search.CommentDetail.ContentInfo = search.CommentDetail.ContentInfo.Trim();
}
//审核人
if (!string.IsNullOrEmpty(search.CommentDetail.CheckUser))
{
search.CommentDetail.CheckUser = search.CommentDetail.CheckUser.Trim();
}
//回复人
if (!string.IsNullOrEmpty(search.CommentDetail.ReplyUser))
{
search.CommentDetail.ReplyUser = search.CommentDetail.ReplyUser.Trim();
}
SearchExpar = search;
return Export("评论导出报表");
}
/// <summary>
/// 设置导出Excel文件的列标题
/// </summary>
/// <returns></returns>
public override IList<string> GetHead()
{
List<string> list = new List<string>();
list.Add("评论ID");
list.Add("会员ID");
list.Add("会员昵称");
list.Add("订单ID");
list.Add("商品ID");
list.Add("商品名字");
list.Add("总评");
list.Add("来源平台");
list.Add("评论内容");
list.Add("评论时间");
list.Add("评论图片");
list.Add("原评论ID");
list.Add("回复内容");
list.Add("回复人");
list.Add("回复时间");
list.Add("拒绝理由");
list.Add("审核人");
list.Add("审核时间");
list.Add("审核状态");
list.Add("是否精华");
return list;
}
/// <summary>
/// 获取导出文件的列标题
/// </summary>
/// <returns></returns>
public override IList<VipCommentProductDetail> GetDataSource()
{
IList<VipCommentProductDetail> exportCommentList = CommentManageClient.Instance.QueryCommentsPageList(SearchExpar).List;
return exportCommentList;
}
public override void OnRowExport(object sender, OnRowExportEventArgs<VipCommentProductDetail> e)
{
try
{
e.helper.SetCellValue("评论ID", e.Data.Id.ToString());
e.helper.SetCellValue("会员ID", e.Data.UserId.ToString());
e.helper.SetCellValue("会员昵称", e.Data.ShowNickName);
e.helper.SetCellValue("订单ID", e.Data.OrderId.ToString());
e.helper.SetCellValue("商品ID", e.Data.ProductId.ToString());
e.helper.SetCellValue("商品名字", e.Data.ProductName);
e.helper.SetCellValue("总评", e.Data.Score.ToString());
e.helper.SetCellValue("来源平台", e.Data.SystemType.ToString());
e.helper.SetCellValue("评论内容", e.Data.ContentInfo);
e.helper.SetCellValue("评论时间", e.Data.AddTime,"DateTime");
e.helper.SetCellValue("评论图片", e.Data.UserImgObj);
e.helper.SetCellValue("原评论ID", e.Data.ParentId>?e.Data.ParentId.ToString():"无");
e.helper.SetCellValue("回复内容", e.Data.ReplyContent);
e.helper.SetCellValue("回复人", e.Data.ReplyUser);
e.helper.SetCellValue("回复时间", e.Data.ReplyTime,"DateTime");
e.helper.SetCellValue("拒绝理由", e.Data.CheckInfo);
e.helper.SetCellValue("审核人", e.Data.CheckUser);
e.helper.SetCellValue("审核时间", e.Data.CheckTime,"DateTime");
e.helper.SetCellValue("审核状态", GetCheckState(e.Data.CheckState));
e.helper.SetCellValue("是否精华", e.Data.IsHighLight > ? "是" : "否");
}
catch (Exception ex)
{
string message = ex.Message;
}
}
//导出前,设置导出的Excel样式等
public override void BeginExport(object sender, BeginExportEventArgs e)
{
//命名sheet,,现在只允许添加一个sheet,添加两个会报错
e.AddSheet("评论管理");
//设置列的宽度
//e.SetColumnWidth("评论时间", 150);
base.BeginExport(sender, e);
}
protected string GetCheckState(int? m)
{
string result = "";
switch (m)
{
case :
result = "未审核";
break;
case :
result = "审核通过";
break;
case :
result = "审核未通过";
break;
}
return result;
}
public abstract class CommonExportController<TEntity> : BaseController, IExportComplexPage<TEntity>
{
protected string FileUrl { get; private set; } /// <summary>
/// 设置导出Excel文件的列标题
/// </summary>
/// <returns></returns>
public abstract IList<string> GetHead(); /// <summary>
/// 获取导出文件的列标题
/// </summary>
/// <returns></returns>
public abstract IList<TEntity> GetDataSource(); /// <summary>
/// 数据导出前事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public virtual void BeginExport(object sender, BeginExportEventArgs e)
{
} public abstract void OnRowExport(object sender, OnRowExportEventArgs<TEntity> e); /// <summary>
/// 导出数据
/// </summary>
/// <param name="fileName">导出文件名称</param>
/// <returns></returns>
[NonAction]
protected ActionResult Export(string fileName = "")
{ IExport export = new GetToolManager().InitExport<TEntity>(this);
string path = base.Server.MapPath(@"~\DownLoad");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
fileName = ExportHelper.GetMatchUrl(fileName, MyFileType.EXCEL);
path = path + @"\" + fileName;
this.FileUrl = path;
this.EncodeStr(Path.GetFileName(path), Encoding.UTF8);
try
{
byte[] file = export.GetFile(MyFileType.EXCEL);
if ((file != null) && (file.Length > ))
{
return this.File(file, "application/ms-excel", base.Url.Encode(fileName));
}
return null;
}
catch (Exception exception)
{
return base.Content("<script>alert('数据导出失败:" + exception.Message + "');</script>");
}
} private string EncodeStr(string str, Encoding coding)
{
str = ExportHelper.GetMatchUrl(str, MyFileType.EXCEL);
string str2 = base.Url.Encode(str);
if (base.Request.Browser.Type.StartsWith("Firefox"))
{
base.Response.HeaderEncoding = coding;
str2 = coding.GetString(coding.GetBytes(str));
}
return str2;
} }
NPOI导出的更多相关文章
- NPOI导出Excel (C#) 踩坑 之--The maximum column width for an individual cell is 255 charaters
/******************************************************************* * 版权所有: * 类 名 称:ExcelHelper * 作 ...
- 基于NPOI导出和导入Excel
概述 NPOI,顾名思义,就是POI的.NET版本.NPOI就是用.NET语言编写的一套数据导出Excel的开源项目,支持XML.xls.xlsx.ppt等格式..NET不仅实现Excel导出还可以实 ...
- (C#)使用NPOI导出Excel
在做业务型的软件时,经常需要将某些数据导出,本文介绍了在Winform或Asp.net中使用NPOI(POI 项目的 .NET 版本)来操作Excel文件,而无需安装Office. 首先,需要获取NP ...
- Asp.Net 使用Npoi导出Excel
引言 使用Npoi导出Excel 服务器可以不装任何office组件,昨天在做一个导出时用到Npoi导出Excel,而且所导Excel也符合规范,打开时不会有任何文件损坏之类的提示.但是在做导入时还是 ...
- C# NPOI导出Excel和EPPlus导出Excel比较
系统中经常会使用导出Excel的功能. 之前使用的是NPOI,但是导出数据行数多就报内存溢出. 最近看到EPPlus可以用来导出Excel,就自己测了下两者导出上的差异. NPIO官网地址:http: ...
- NPOI导出EXCEL 打印设置分页及打印标题
在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方法,但一直都没有起到作用.经过研究是要设置 sheet1.FitToPage = false; 而 ...
- .NET NPOI导出Excel详解
NPOI,顾名思义,就是POI的.NET版本.那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office的文件. 支持的文件格式包括xls, ...
- NPOI导出Excel(含有超过65335的处理情况)
NPOI导出Excel的网上有很多,正好自己遇到就学习并总结了一下: 首先说明几点: 1.Excel2003及一下:后缀xls,单个sheet最大行数为65335 Excel2007 单个sheet ...
- [转]NPOI导出EXCEL 打印设置分页及打印标题
本文转自:http://www.cnblogs.com/Gyoung/p/4483475.html 在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方 ...
- NPOI导出模板样式
/// <summary> /// 导出多种车辆统计表格 /// </summary> /// <returns></returns> [ActionN ...
随机推荐
- 用wget扒站时遇到电信劫持
今天用wget扒下来一个html template的站. 挂在自己机器上后随便点什么,都出电信广告.仔细检查,我勒个去... 扒站过程中,刚好被电信打了劫,看看它给我下载下来的bootstrap.mi ...
- C+命令行+方向键=简易版扫雷
前言: 想起来做这个是因为那时候某天知道了原来黑框框里面的光标是可以控制的,而且又经常听人说起这个,就锻炼一下好了. 之前就完成了那1.0的版本,现在想放上来分享却发现有蛮多问题的,而且最重要的是没什 ...
- asp.net 导出Excel
分享一个asp.net 导出假Excel代码.优点,不用借助于任何插件比如(NPOI),复制代码,修改grid.DataSource直接导出. 先看导出后的效果图 System.Web.UI.WebC ...
- php cli方式下获取服务器ip
(未整理....) (1)php cli方式下获取服务器ip [php] function getServerIp(){ $ss = exec('/sbin/ifconfig et ...
- mysql禁用autocommit,以及遇到的问题
原文地址:http://blog.51yip.com/mysql/1230.html http://blog.csdn.net/ying_593254979/article/details/12095 ...
- JQuery入门——进度条
越来越觉得常规javascript已经跟不上节奏了,打算学点进阶的,从JQuery学起. JQuery是一个Javascript库,可以从JQuery.com下载,放到本地,用 <script ...
- emacs 新手笔记(三) —— 为 emacs 做一点简单的定制
ilocker:关注 Android 安全(新入行,0基础) QQ: 2597294287 在 emacs 启动时,会加载 ~/.emacs 文件.在该文件中编辑一些 lisp 代码,是一种最为简单的 ...
- PS色调均化滤镜的快捷实现(C#源代码)。
photoshop色调均化功能通常是在进行修片处理前期比较常用的功能之一,其对扩展图像的对比度,增强视觉效果有一定的作用.在很多课本或者文章中,也称这种处理为灰度均衡化.直方图均衡化等等.算法原理都是 ...
- 洛谷八月月赛Round1凄惨记
个人背景: 上午9:30放学,然后因为学校举办读书工程跟同学去书城选书,中午回来开始打比赛,下午又回老家,中间抽出一点时间调代码,回家已经8:50了 也许是7月月赛时“连蒙带骗”AK的太幸运然而因同学 ...
- 06章 Struts2国际化
1:什么是国际化? 国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式.它要求从产品中抽离所有的与语言,国家/地区和文化相关的元素.换言之,应用程序的功 ...