// 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导出的更多相关文章

  1. NPOI导出Excel (C#) 踩坑 之--The maximum column width for an individual cell is 255 charaters

    /******************************************************************* * 版权所有: * 类 名 称:ExcelHelper * 作 ...

  2. 基于NPOI导出和导入Excel

    概述 NPOI,顾名思义,就是POI的.NET版本.NPOI就是用.NET语言编写的一套数据导出Excel的开源项目,支持XML.xls.xlsx.ppt等格式..NET不仅实现Excel导出还可以实 ...

  3. (C#)使用NPOI导出Excel

    在做业务型的软件时,经常需要将某些数据导出,本文介绍了在Winform或Asp.net中使用NPOI(POI 项目的 .NET 版本)来操作Excel文件,而无需安装Office. 首先,需要获取NP ...

  4. Asp.Net 使用Npoi导出Excel

    引言 使用Npoi导出Excel 服务器可以不装任何office组件,昨天在做一个导出时用到Npoi导出Excel,而且所导Excel也符合规范,打开时不会有任何文件损坏之类的提示.但是在做导入时还是 ...

  5. C# NPOI导出Excel和EPPlus导出Excel比较

    系统中经常会使用导出Excel的功能. 之前使用的是NPOI,但是导出数据行数多就报内存溢出. 最近看到EPPlus可以用来导出Excel,就自己测了下两者导出上的差异. NPIO官网地址:http: ...

  6. NPOI导出EXCEL 打印设置分页及打印标题

    在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方法,但一直都没有起到作用.经过研究是要设置  sheet1.FitToPage = false; 而 ...

  7. .NET NPOI导出Excel详解

    NPOI,顾名思义,就是POI的.NET版本.那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office的文件. 支持的文件格式包括xls, ...

  8. NPOI导出Excel(含有超过65335的处理情况)

    NPOI导出Excel的网上有很多,正好自己遇到就学习并总结了一下: 首先说明几点: 1.Excel2003及一下:后缀xls,单个sheet最大行数为65335 Excel2007 单个sheet ...

  9. [转]NPOI导出EXCEL 打印设置分页及打印标题

    本文转自:http://www.cnblogs.com/Gyoung/p/4483475.html 在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方 ...

  10. NPOI导出模板样式

    /// <summary> /// 导出多种车辆统计表格 /// </summary> /// <returns></returns> [ActionN ...

随机推荐

  1. python简单爬虫定时推送同花顺直播及荐股至邮箱

    1.初衷:实践 2.技术:python requests Template 3.思路:根据直播页面获取评价最高的前十博主,定时爬行最新的消息和实战股票 4.思路:python 编辑简单邮件html模板 ...

  2. 在java中使用RBL服务器(中国反垃圾邮件联盟的CBL+使用)

    这是06年写的,不知道现在RBL改了没,不过恢复过来做记录,以后可能需要. 实时黑名单(RBL)实际上是一个可供查询的IP地址列表,通过DNS的查询方式来查找一个IP地址的A记录是否存在来判断其是否被 ...

  3. React-Native测试报告

     React-native 使用js编写android和ios程序,前端时间开始支持android,本人根据官方的教程,先安装开发环境,然后运行hello world,最后看了下官方提供的实例程序UI ...

  4. java 自动装箱自动拆箱

    1.Java数据类型 在介绍Java的自动装箱和拆箱之前,我们先来了解一下Java的基本数据类型. 在Java中,数据类型可以分为两大种,Primitive Type(基本类型)和Reference ...

  5. FastCV安装报错---LaunchAnyWhere错误:载入Java VM时Windows出现错误:2

  6. Vim命令大全

    1.进入vi的命令 vi filename :打开或新建文件,并将光标置于第一行首 vi +n filename :打开文件,并将光标置于第n行首 vi + filename :打开文件,并将光标置于 ...

  7. AC日记——单词翻转 1.7 27

    27:单词翻转 总时间限制:  1000ms 内存限制:  65536kB 描述 输入一个句子(一行),将句子中的每一个单词翻转后输出. 输入 只有一行,为一个字符串,不超过500个字符.单词之间以空 ...

  8. 紫书例题-Ancient Cipher

    Ancient Roman empire had a strong government system with various departments, including a secret ser ...

  9. java 27 - 5 反射之 通过反射获取成员方法并使用

    类Method:提供关于类或接口上单独某个方法(以及如何访问该方法)的信息. A:获取所有方法 数组 1.getMethods  获取该类包括其父类的公共成员方法 2.getDeclaredMetho ...

  10. tyvj[1087]sumsets

    描述     正整数N可以被表示成若干2的幂次之和.例如,N = 7时,共有下列6种不同的方案:1) 1+1+1+1+1+1+12) 1+1+1+1+1+23) 1+1+1+2+24) 1+1+1+4 ...