@using (Html.BeginForm("Student", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ <div style="margin-top: 20px;">
<fieldset id="myfieldset1">
<legend>学生信息导入</legend>
<p>
选择文件:<input id="FileUpload1" type="file" name="files" style="width: 250px; height: 24px;
background: White" class="easyui-validatebox" /></p>
<p>
<input id="btnImport1" type="submit" value="导入" style="width: 60px; height: 28px;" /></p>
<p style="color: Red; text-align: center;">@ViewBag.errorstu</p>
</fieldset>
</div>
}
     public class ExcelController : Controller
{
ContractInfoBLL contract;
TeacherInfoBLL TIBLL;
ParentBLL PBLL;
public ExcelController()
{
if (contract == null)
{
contract = new ContractInfoBLL();
}
if (TIBLL == null)
{
TIBLL = new TeacherInfoBLL();
}
if (PBLL == null)
{
PBLL = new ParentBLL();
}
}
public ActionResult Index(bool Code = true, string Message="")
{
if (!Code)
{
ViewBag.Message = Message;
}
return View();
}
string StuExcel = ApiHelper.GetWebConfig("StuExcel", @"E:/需求/20160520 家宝贝/新建文件夹/学生用户.xlsx");
/// <summary>
/// Excel学生用户导入
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult Student(HttpPostedFileBase filebase)
{
#region
HttpPostedFileBase file = Request.Files["files"];
string FileName;
string savePath;
if (file == null || file.ContentLength <= )
{
ViewBag.error = "文件不能为空";
return View();
}
else
{
string filename = Path.GetFileName(file.FileName);
int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
string fileEx = System.IO.Path.GetExtension(filename);//获取上传文件的扩展名
string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
int Maxsize = * ;//定义上传文件的最大空间大小为4M
string FileType = ".xls,.xlsx";//定义上传文件的类型字符串 FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
if (!FileType.Contains(fileEx))
{
ViewBag.error = "文件类型不对,只能导入xls和xlsx格式的文件";
return View();
}
if (filesize >= Maxsize)
{
ViewBag.error = "上传文件超过4M,不能上传";
return View();
}
string path = AppDomain.CurrentDomain.BaseDirectory + "App_Data/";
savePath = Path.Combine(path, FileName);
file.SaveAs(savePath);
}
#endregion
List<Student_Excel> stuList = new ExcelBLL().GetStudentByExcel(savePath);
string Meg = "";
int ItemSchool = ;
int classID = ;
int i = ;
foreach (var item in stuList)
{ bool ishavecode = contract.IsHaveContractCode(item.ContractCode);
if (!ishavecode)
{
i++;
Meg = "学籍号重复";
LoggerFactory.Instance.Logger_Info("学生用户_序号" + item.Number + "_学籍号:" + item.ContractCode + "_学生姓名:" + item.Name + "_原因:" + Meg);
}
else
{
ItemSchool = contract.GetGardenByName(item.ItemSchoolName);
classID = contract.GetClassInfoID(ItemSchool, item.ClassName);
if (classID != )
{
DateTime da = DateTime.Now;
ContractInfoList model = new ContractInfoList();
model.ContractCode = item.ContractCode;
model.ContractStatus = (int)ContractStatus.Normal;
model.AdmissionsTeacherID = contract.GetTeacherIDbyName(item.TeacherName);
model.StudentName = item.Name;
model.StudentGender = item.Sex == "男" ? : ;
model.ParentName = item.ParentName;
model.ParenRelation = item.ParenRelation;
model.ParentTel = item.Phone;
model.EntranceTime = item.EntranceTime.HasValue ? item.EntranceTime.Value : DateTime.Now;
model.PaymentAmount = item.PaymentAmount != "" ? Convert.ToInt32(item.PaymentAmount) : ;
model.ItemSchool = ItemSchool;
model.AddTime = da;
model.UpdateTime = da;
model.Remarks = "";
model.ClassInfoID = classID; bool boo = contract.IsCreateContract(model);
if (!boo)
{
i++;
Meg = "创建失败";
LoggerFactory.Instance.Logger_Info("学生用户_序号" + item.Number + "_学籍号:" + item.ContractCode + "_学生姓名:" + item.Name + "_原因:" + Meg);
}
}
else
{
i++;
Meg = "班级不存在";
LoggerFactory.Instance.Logger_Info("学生用户_序号" + item.Number + "_学籍号:" + item.ContractCode + "_学生姓名:" + item.Name + "_原因:" + Meg);
}
}
} return Json(new { Code = Meg == "" ? true : false, Message = Meg != "" ? "未导入数据:" + i + "条" : "" });
//ViewBag.errorstu = "导入成功";
//return RedirectToAction("Index");
} }
     public class ExcelBLL
{
public List<Student_Excel> GetStudentByExcel(string path)
{
List<Student_Excel> stuList = new List<Student_Excel>();
DataSet ds = Helper.GetDataSet("select * from [Sheet1$]", path);
DataTable dt = ds.Tables[];//忽略第一行表名,从第二行开始
foreach (DataRow row in dt.Rows)
{
if (row["序号"].ToString()!="")
{
DateTime ad = new DateTime();
if (row["入学日期"].ToString() != "")
{
ad = Convert.ToDateTime(row["入学日期"]);
}
stuList.Add(new Student_Excel()
{
Number = row["序号"].ToString(),
ContractCode = row["学籍号"].ToString(),
Name = row["学生姓名"].ToString(),
Sex = row["性别"].ToString(),
ClassName = row["所在班级"].ToString(),
Phone = row["紧急联系电话"].ToString(),
ParenRelation = row["与孩子关系"].ToString(),
ParentName = row["家长姓名"].ToString(),
EntranceTime = ad,//Convert.ToDateTime(row["入学日期"]),
TeacherName = row["招生老师"].ToString(),
PaymentAmount = row["收费金额"].ToString(),
ItemSchoolName = row["所在园区"].ToString(),
});
}
} return stuList;
}
}
      public class Helper:BaseBLL
{
#region Excel 导入
private static string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=yes; IMEX=2'"; public static DataSet GetDataSet(string sql, string path)
{
OleDbConnection conn = new OleDbConnection(string.Format(connstring, path));
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();//创建内存数据集
try
{
conn.Open();
da.Fill(ds);
return ds;
}
catch (Exception e)
{
//写日志 throw e;
}
finally
{
conn.Close();
}
}
#endregion
}

Excel 数据导入(OleDb)的更多相关文章

  1. C#使用oledb方式将excel数据导入到datagridview后数据被截断为 255 个字符

    问题描述:在使用oledb方式将excel数据导入到datagridview中,在datagridview单元格中的数据没有显示全,似乎只截取了数据源中的一段 解决方案:1.关于该问题,微软官方答案: ...

  2. c#将Excel数据导入到数据库的实现代码(OleDb)

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

  3. 效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中【附源代码下载】) 转

    效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中[附源代码下载])    本文目录: (一)背景 (二)数据库数据导入到Excel的方法比较   ...

  4. excel 数据导入数据表

    环境: Windows server 2012  rm sql server  2012 excel 数据导入数据表 INSERT INTO [dbo].[AdminUser] SELECT [Adm ...

  5. excel数据导入到sqlserver中---------工作笔记

    调用页面: using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sys ...

  6. c#将Excel数据导入到数据库的实现代码(转载)

    假如Excel中的数据如下:     数据库建表如下:     其中Id为自增字段:      代码如下: using System; using System.Collections.Generic ...

  7. C#将Excel数据导入数据库(MySQL或Sql Server)

    最近一直很忙,很久没写博客了.今天给大家讲解一下如何用C#将Excel数据导入Excel,同时在文章最后附上如何用sqlserver和mysql工具导入数据. 导入过程大致分为两步: 1.将excel ...

  8. C# Excel数据导入到数据库

    http://www.jb51.net/article/44743.htm 假如Excel中的数据如下: 数据库建表如下: 其中Id为自增字段: 代码: 复制代码 代码如下: using System ...

  9. 批量Excel数据导入Oracle数据库

    由于一直基于Oracle数据库上做开发,因此常常会需要把大量的Excel数据导入到Oracle数据库中,其实如果从事SqlServer数据库的开发,那么思路也是一样的,本文主要介绍如何导入Excel数 ...

  10. c#将Excel数据导入到数据库的实现代码

    这篇文章主要介绍了c#将Excel数据导入到数据库的实现代码,有需要的朋友可以参考一下 假如Excel中的数据如下: 数据库建表如下: 其中Id为自增字段: 代码: 代码如下: using Syste ...

随机推荐

  1. Android中的ScrollTo和ScrollBy解析

    关于Android中的ScrollBy和ScrollTo方法相信大家并不陌生,这两个方法是在View中实现的.所以在各个继承了View的类都可以使用改方法. 在View中对这两个方法的源码编写是这样的 ...

  2. ABC: Always Be Coding

    ABC: Always Be Coding (原地址:https://medium.com/@davidbyttow/abc-always-be-coding-d5f8051afce2)   Be h ...

  3. Pycharm集成PyQt4并使用

  4. build.gradle代码

    Android Studio 这么强大的工具,就算我们不懂 gradle, groovy, 也照样能借助AS对 Android 项目进行编译.调试.运行.打包等操作.build.gradle 这个文件 ...

  5. 虚拟机Linux 的一些基础命令和注释

    cd命令 cd    ==回到初始,主目录 cd -  ==回到上一级目录交替 cd ~ ==回到root家目录 cd .  ==当前目录 cd .. ==进入上一级目录 ls命令 ls     == ...

  6. Java基础学习(六)—List

    一.List 1.List集合特有功能 /* * List集合的特有功能: * A:添加功能 * void add(int index,Object element):在指定位置添加元素 * B:获取 ...

  7. Service详解

    /** * 后台执行的定时任务 */ public class LongRunningService extends Service { @Override public IBinder onBind ...

  8. ValueStack

    1.把list集合压入栈顶 /** * * 查找所有的用户 * @return */ public String findAll() { List<User> allUser = user ...

  9. CocoaAsyncSocket + Protobuf 处理粘包和拆包问题

    在上一篇文章<iOS之ProtocolBuffer搭建和示例demo>分享环境的搭建, 我们和服务器进行IM通讯用了github有名的框架CocoaAsynSocket, 然后和服务器之间 ...

  10. 浩哥解析MyBatis源码(十)——Type类型模块之类型处理器

    原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6715063.html 1.回顾 之前的两篇分别解析了类型别名注册器和类型处理器注册器,此二 ...