• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

View视图部分:

<form method="post" enctype="multipart/form-data" action="/Position/ImportExcel" class="form-group">
<input name="file" type="file" ></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
)


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
[翻译]ASP.NETWebAPI中的异常处理发布时间:2022-07-10
下一篇:
从源码看ASP.NET框架(一)-打造页面控件树发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap