做項目遇到一個問題,怎麼不保存上傳的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;
}
大功告成。。。