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 ...
随机推荐
- Nginx问题定位之监控进程异常退出
nginx在运行过程中是否稳定,是否有异常退出过?这里总结几项平时会用到的小技巧. 1. 在error.log中查看是否有signal项,如果有,看看signal是多少. 比如,这是一个异常退出的情况 ...
- 关于InnoDB的Next-Key lock
最近一段时间在准备新员工培训的材料,本来打算介绍介绍概念就OK的,但是既然写了事务的章节,就特别想介绍一下锁,介绍了锁,就忍不住想介绍一下Next-Key Lock. 大家知道,标准的事务隔离级别有R ...
- mongoDB怎样拷贝一个collection从一个数据库到另一个在同一个主机上
new_database是目的数据库 db.<collection_name>.find().forEach(function(d){ db.getSiblingDB('<new_d ...
- 像编程一样写文章—Markdown
Markdown是什么 是一种极其简单的标记语言,写的时候只需要普通编辑器即可: 它可以使文本内存具有某种格式: Markdown设计理念使文本易读.易写 文件后缀名:.md . .markdown. ...
- Jmeter之Bean shell使用(一)
一.什么是Bean Shell BeanShell是一种完全符合Java语法规范的脚本语言,并且又拥有自己的一些语法和方法; BeanShell是一种松散类型的脚本语言(这点和JS类似); BeanS ...
- ASP.NET 跨域
#region 支持跨域请求 //Response.ClearHeaders(); string origin = Request.Headers["Origin"]; Respo ...
- Windows 安装ELK
在Windows服务器上安装ELK logstash在windows平台下不能监控磁盘文件,用nxlog代替,监控文件并把内容发送到logstash 部署环境 Os :Windows 7 logsta ...
- viso2010从mysql中导出ER图
mysql connector 下载地址: http://dev.mysql.com/downloads/connector/odbc/5.1.html 首先机器要安装mysql-connector- ...
- putty-不输入密码直接登陆
在桌面建立新的快捷方式,命令行填写如下: d:\soft\putty.exe -pw 你的口令 用户名@服务器地址注意更换你的putty.exe的路径,为了避免出错,这里有个窍门,你可以找到putty ...
- vmware虚拟机 32位Ubuntu 安装matlab_R2012A问题小记
最近由于学校课程的需要,所以在Ubuntu上捣腾了一下matlab,经历曲折,记录一下,希望能让大家少跳点坑.先分享一个有效的下载链接: http://www.matlab.org.cn/Downlo ...