做项目遇到一个问题,怎么不保存上传的excel ,直接将处理结果存入数据库,看到常用的nopi都是读的文件流,很是头疼。一番功夫后终于解决了
首先页面代码
@using (Ajax.BeginForm(
"GetFile",
"MainTable",
ajaxOptions: new AjaxOptions
{
//InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "alt1"
},
htmlAttributes: new
{
id = "searchFrom1",
Enctype = "multipart/form-data"
//UpdateTargetId = "_MainTableListDiv"
}
))
{
<div class="form-group">
<input type="file" onchange="$('#subfile').click()" name="sd" id="file" style="display:none" />
<input type="button" onclick="$('#file').click()" value="上传文件" class="btn btn-success" />
<input type="submit" id="subfile" style="display:none" class="btn btn-danger" value="提交" />
@Html.ActionLink("下载附件", "DownLoadFile", "MainTable",new { @class="btn btn-sussess"})
</div>
}
form 表单 内嵌文件控件,再来个按钮模拟点击提交
后台代码
public ActionResult GetFile()
{
try
{
bool re = false;
JavaScriptResult aScriptResult = new JavaScriptResult();
HttpPostedFileBase aa = Request.Files[Request.Files.Count - 1];//获得最后一个文件
List<MainTableZi> lz = <span style="color:#ff0000;">ExcelHelper.GetList<MainTableZi></span>(aa.InputStream, "MainTableZi", "MTZ", 2, 0);//这里是核心函数,
}
}
将excel文件导出为集合 /// <summary>
/// 将excel导出为类列表
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="str">文件流</param>
/// <param name="SheetName">工作表名称</param>
/// <param name="FirstW">字段前缀</param>
/// <param name="startClo">数据开始的行数(从零开始)</param>
/// <param name="descripClo">字段描述行所在的行数</param>
/// <returns></returns>
public static List<T> GetList<T>(Stream str,string SheetName,string FirstW,int startClo,int descripClo) {
List<T> a = new List<T>();
MemoryStream de = new MemoryStream();
str.CopyTo(de);
//初始化流位置
str.Position = 0;
de.Position = 0;
IWorkbook workbook = null;
try
{
workbook = new XSSFWorkbook(de);
}
catch (Exception ex)
{
workbook = new HSSFWorkbook(de);
}
ISheet sheet = workbook.GetSheet(SheetName);
int firstNum = startClo;//数据开始行数
int colNameNum =descripClo;//字段行所在行数
if (sheet.LastRowNum >= firstNum) {
IRow row = sheet.GetRow(colNameNum);//获得字段描述行
for (int i = firstNum; i <= sheet.LastRowNum; i++)
{
// T nt = new T();
T nt = Activator.CreateInstance<T>();
MemberInfo[] properties = nt.GetType().GetMembers();
for (int j = 0; j < row.LastCellNum; j++)
{
PropertyInfo pi= nt.GetType().GetProperty(FirstW+"_"+row.GetCell(j).StringCellValue);
if (pi != null) {
var ce= sheet.GetRow(i).GetCell(j);//获得单元格的值
if (ce != null) {
pi.SetValue(nt, ce.ToString());
}
}
}
a.Add(nt);
}
}
return a;
}
大功告成。。。