码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET MVC 导入Excel文件(完整版)

时间:2020-06-27 19:51:18      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:har   保存   submit   连接数   扩展   状态   btn   eric   create   

View视图部分:

<form method="post" enctype="multipart/form-data" action="/Position/ImportExcel" class="form-group">
<input name="file" type="file" id="file" />
<button id="btn_import" type="submit" class="btn btn-info">
<span class="glyphicon glyphicon-pencil"></span>导入
</button>
</form>

控制器部分:

public ActionResult ImportExcel()
{
//获取上传的Excel文件
HttpPostedFileBase File = Request.Files["file"];
string message = "";
if (File.ContentLength > 0)
{
//GetExtension:返回指定路径的文件的扩展名
var Isxls = System.IO.Path.GetExtension(File.FileName).ToString().ToLower();
if (Isxls != ".xls" && Isxls != ".xlsx")
{
message = "<script>alert(‘请上传Excel文件‘),window.location.href=‘/Position/Index‘</script>";
}
var FileName = File.FileName;//获取文件夹名称
var path = Server.MapPath("~/FileExcel/" + FileName);
File.SaveAs(path);//将文件保存到服务器
PositionBLL bll = new PositionBLL();
var list = bll.FileUpLoad(path);
if (list.Count > 0)
{
int num = bll.LoadFile(list);
if (num > 0)
{
message = "<script>alert(‘数据导入成功‘),window.location.href=‘/Position/Index‘</script>";
}
}
else
{
message = "<script>alert(‘导入的数据不能为空‘),window.location.href=‘/Position/Index‘</script>";
}
}
else
{
message = "<script>alert(‘请选择上传的文件‘),window.location.href=‘/Position/Index‘</script>";
}
return Content(message);
}

Model部分:

public class PositionModel
{
string PositionName;
string Qualification;
string Remark;

public string PositionName1 { get => PositionName; set => PositionName = value; }
public string Qualification1 { get => Qualification; set => Qualification = value; }
public string Remark1 { get => Remark; set => Remark = value; }
}

PositionBLL部分:

public class PositionBLL
{
//private const string ConnString2003 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=‘Excel 8.0‘;HDR=‘Yes‘";
//链接打开excel的字符串
private const string ConnString2003 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=‘Excel 8.0‘;";
public List<PositionModel> FileUpLoad(string filePath)
{
DataSet ds = new DataSet();
List<PositionModel> list = new List<PositionModel>();
string strSQL = string.Format(ConnString2003, filePath);
//OleDbConnection:表示与数据源的开放链接
OleDbConnection conn = new OleDbConnection(strSQL);
try
{
//判断连接的状态
if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
{
conn.Open();
}
DataTable tableName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//获取Excel的第一个Sheet名称
var sheetName = tableName.Rows[0]["TABLE_NAME"].ToString().Trim();
string SQL = "select * from [" + sheetName + "]";
OleDbDataAdapter sa = new OleDbDataAdapter(SQL, conn);
sa.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
PositionModel model = new PositionModel();
model.PositionName1 = dr["职位名称"].ToString();
model.Qualification1 = dr["任职资格"].ToString();
model.Remark1 = dr["职位描述"].ToString();
list.Add(model);
}
}
catch (Exception ex)
{
Console.WriteLine("错误信息:PositionBLL+FileUpLoad方法" + ex);
}
return list;
}
//将数据循环遍历到数据库中
PositionDAL dal = new PositionDAL();
public int LoadFile(List<PositionModel> list)
{
var num = 0;
foreach (var item in list)
{
PositionModel model = new PositionModel();
model.PositionName1 = item.PositionName1;
model.Qualification1 = item.Qualification1;
model.Remark1 = item.Remark1;
num = dal.Add(model);
}
return num;
}

PositionDAL部分:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ExcleImport.Models
{

public class PositionDAL
{
DBhelper dBhelper = new DBhelper();
public int Add(PositionModel model) {

string sql = string.Format("insert into userInfo (position,grade,remark)values(‘{0}‘,‘{1}‘,‘{2}‘)", model.PositionName1, model.Qualification1, model.Remark1);
return dBhelper.ExceDml(sql);
}
}
}

DBhelper部分:

//创建链接数据库的字符串
string dbStr = "Data Source=.;Initial Catalog=sales;Integrated Security=True";
public int ExceDml(string sql)
{
try
{
int res = 0;
//连接数据库
using (SqlConnection conn = new SqlConnection(dbStr))
{
//打开连接数据库
conn.Open();
//执行sql
SqlCommand comm = new SqlCommand(sql, conn);
res = comm.ExecuteNonQuery();
}
return res;
}
catch (Exception ex)
{
Console.WriteLine("错误信息:DBhelper+ExceDml方法" + ex);
throw ex;
}

}

数据库表:

create table userInfo
(
id int identity(1,1)not null,
position varchar(50)not null,
grade varchar(50)not null,
remark varchar(100)not null
)

ASP.NET MVC 导入Excel文件(完整版)

标签:har   保存   submit   连接数   扩展   状态   btn   eric   create   

原文地址:https://www.cnblogs.com/ypyp123/p/13199251.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!