前台代码:
html:
<div class="panel panel-primary" style="max-width:400px;float:left;margin-left:20px;">
<div class="panel-heading">
<span class="glyphicon glyphicon-bullhorn" aria-hidden="true"></span>
密度导入
</div>
<form id="frm" name="frm" method="post" style="margin-top:18px;">
<input type="file" class="file" name="density" data-show-upload="false" data-show-delete="false" />
</form>
<label id="beforeSucc"></label>
<hr/>
<div style="position:relative;margin:5px;margin-right:10px!important;width:auto;margin-left:auto;text-align:right;">
<a class="btn btn-danger" data-toggle="modal" id="FrmBtn" >导入</a>
@*<a class="btn btn-primary" onclick="document.execCommand('Refresh')">刷新</a>*@
</div>
</div>
js:
$('#FrmBtn').click(function(){
$.ajax({
url:'/Params/DensityIn',
type:'POST',
contentType: false,
processData: false,
data: new FormData($('#frm')[0]),
beforeSend: function(){
$('#beforeSucc').text('正在导入,请稍后...');
},
success:function(data){
if (data=="导入成功") {
alert("导入成功!");
}
if (data=="文件读取失败") {
alert("文件读取失败!");
}
if (data=="提交了重复数据") {
alert("提交了重复数据!");
}
$('#beforeSucc').hide();
},
error:function(){
alert("error");
}
})
});
后台代码:
//密度上传
public JsonResult DensityIn()
{
if (Request.Files.Count>0)
{
HttpPostedFileBase file = Request.Files[0];
var fileName = file.FileName;
string filePath = "/UpLoad/MD/" + fileName;
string AbsolutePath = Server.MapPath(filePath);
file.SaveAs(AbsolutePath);
//读取excel数据
var datableData = ExcelToDataTable(AbsolutePath);
//excel数据转换为list
var list = CommonTransafer.ToList<YLGL_MDHS>(datableData);
//数据库数据
var mdList = (from a in db.YLGL_MDHS
select a).ToList();
//获取不重复数据
var exp = list.Where(a => (!mdList.Exists(t => a.MDHS_SMD.Equals(t.MDHS_SMD) && a.MDHS_WD.Equals(t.MDHS_WD)))).Distinct().ToList();
var insert = new YLGL_MDHS() { };
if (exp.Count() > 0)
{
foreach (var item in exp)
{
insert.MDHS_WD = item.MDHS_WD;
insert.MDHS_SMD = item.MDHS_SMD;
insert.MDHS_BMD = item.MDHS_BMD;
db.YLGL_MDHS.Add(insert);
}
db.SaveChanges();
return Json("导入成功");
}
else
{
return Json("提交了重复数据");
}
}
return Json("文件读取失败");
}
/// <summary>
/// DataTable 转换为List 集合
/// </summary>
/// <typeparam name="TResult">类型</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static DataTable ExcelToDataTable(string filePath)
{
try
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
string fileExt = Path.GetExtension(filePath);
IWorkbook workbook = null;
if (fileExt == ".xls")
{
workbook = new HSSFWorkbook(fs);
}
else if (fileExt == ".xlsx")
{
workbook = new XSSFWorkbook(fs);
}
ISheet sheet = workbook.GetSheetAt(0);
int rfirst = sheet.FirstRowNum;
int rlast = sheet.LastRowNum;
IRow row = sheet.GetRow(rfirst);
int cfirst = row.FirstCellNum;
int clast = row.LastCellNum;
for (int i = cfirst; i < clast; i++)
{
if (row.GetCell(i) != null)
dt.Columns.Add(row.GetCell(i).StringCellValue, System.Type.GetType("System.String"));
}
row = null;
for (int i = rfirst + 1; i <= rlast; i++)
{
DataRow r = dt.NewRow();
IRow ir = sheet.GetRow(i);
for (int j = cfirst; j < clast; j++)
{
if (ir.GetCell(j) != null)
{
r[j] = ir.GetCell(j).ToString();
}
}
dt.Rows.Add(r);
ir = null;
r = null;
}
sheet = null;
workbook = null;
}
return dt;
}
catch (Exception)
{
throw;
}
}
类CommonTransafer:
/// <summary>
/// DataTable 转换为List 集合
/// </summary>
/// <typeparam name="TResult">类型</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
//创建一个属性的列表
List<PropertyInfo> prlist = new List<PropertyInfo>();
//获取TResult的类型实例 反射的入口
Type t = typeof(T);
//获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表
Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
//创建返回的集合
List<T> oblist = new List<T>();
foreach (DataRow row in dt.Rows)
{
//创建TResult的实例
T ob = new T();
//找到对应的数据 并赋值
prlist.ForEach(p =>
{
try
{
if (row[p.Name] != DBNull.Value)
{
object obj = row[p.Name];
PropertyInfo ptyInfo = ob.GetType().GetProperty(p.Name);
Type coltyp = ptyInfo.PropertyType;
if (coltyp.IsGenericType && coltyp.GetGenericTypeDefinition() == typeof(Nullable<>))
{
coltyp = coltyp.GetGenericArguments()[0];
}
if (p.Name.Equals("DepartmentId") || p.Name.Equals("CardTypeId"))
p.SetValue(ob, Convert.ToInt32(obj.ToString().Trim()), null);
else
p.SetValue(
ob,
Convert.ChangeType(obj, coltyp),
null);
}
}
catch (Exception)
{
}
});
//放入到返回的集合中.
oblist.Add(ob);
}
return oblist;
}
截图: