Asp.Net Mvc上传Excel数据(NPOI)
后台代码
[System.Web.Mvc.HttpPost]
public ActionResult UpLoadFile(HttpPostedFileBase file)
{
string BatchName = Request.Form["BatchName"];
DataTable dt = ExcelHelper.ExcelByStreamToTable(file.InputStream);
dt.Columns["编号"].ColumnName = "USERNO";
dt.Columns["姓名"].ColumnName = "USERNAME";
dt.Columns["一级部门名称"].ColumnName = "DEPT1";
dt.Columns["二级部门名称"].ColumnName = "DEPT2";
dt.Columns["三级部门名称"].ColumnName = "DEPT3";
dt.Columns["联系电话"].ColumnName = "USERTEL";
dt.Columns["常驻工作地"].ColumnName = "OFFERADDR";
List<TB_Com_UserModel> model = ModelConvertHelper<TB_Com_UserModel>.ConvertToModel(dt).ToList();
model.ForEach(x => { x.VALID = 1; x.COMSTATUS = 0; x.BID = Convert.ToInt32(BatchName); x.CREATETIME = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); });
var result = CallService("api_url", "User/ImportItem", model);
return Json(result, JsonRequestBehavior.AllowGet);
}
| 我们在获取到File对象之后(Npoi)读取文件的表格。将其转换成DataTable。之后转换成对应实体类的List。最后进行业务逻辑处理
public static DataTable ExcelByStreamToTable(Stream stream)
{
DataTable dt = new DataTable();
IWorkbook workbook;
try
{
workbook = new XSSFWorkbook(stream);
}
catch (Exception ex)
{
workbook = new HSSFWorkbook(stream);
}
ISheet sheet = workbook.GetSheetAt(0);
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = 0; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
return dt;
}
public class ModelConvertHelper<T> where T : new()
{
public static IList<T> ConvertToModel(DataTable dt)
{
IList<T> ts = new List<T>();
Type type = typeof(T);
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value) pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
| 好的,到了这一步,那我们的前端也是要说下怎么传递。
ImportData:function(){
if($("#form-category-add").valid()){
if($("input[type='file']").val() != "" && $('#BATCHNAME option:Selected').val() != ""){
var dataParams = {
BatchName: $('#BATCHNAME option:Selected').val()
};
var opt = {
type :'post',
dataType: 'json',
url: '/User/UpLoadFile',
data:dataParams,
success: function (result) {
if (result.Code == "10000") {
parent.layer.msg(result.Data, { icon: 6 });
setTimeout(function () {
var index = parent.layer.getFrameIndex(window.name);
if (index) {
parent.layer.close(index);
}
}, 500);
} else {
parent.layer.msg(result.Message, { icon: 5 });
}
},
error: function (e){
parent.layer.msg('导入出错', { icon: 5 });
}
};
$('#UploadFile').ajaxSubmit(opt);
}else{
layer.msg("请选择文件",{icon:5});
}
}
},
| 前端页面
<form id="UploadFile" action="" method="post" class="form form-horizontal">
<div class="formControls col-xs-10 col-sm-10">
<input id="FileName" type="text" disabled="disabled" class="input-text radius" />
</div>
<a href="javascript:;" class="file">
选择文件
<input id="FileInput" type="file" name="file" accept=".xls,.xlsx" value=" " />
</a>
<div class="mt-15 mb-10" style="text-align:center">
<a href="/User/DownloadFile" name="btnDown" id="btnDown" class="btn btn-info radius" style="height: 40px;width:80px;">
<i class="Hui-iconfont">&
</a>
<button type="button" name="btnSave" id="btnSave" class="btn btn-secondary radius" style="height:30px;width:70px;margin-left:3%;">
<i class="Hui-iconfont">&
</button>
</div>
</form>
|