public ActionResult TestExcel(string filePath)
{
return View();
}
/// <summary>
/// 根据Excel列类型获取列的值
/// </summary>
/// <param name="cell">Excel列</param>
/// <returns></returns>
private static string GetCellValue(ICell cell)
{
if (cell == null)
return string.Empty;
switch (cell.CellType)
{
case CellType.Blank:
return string.Empty;
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
case CellType.Error:
return cell.ErrorCellValue.ToString();
case CellType.Numeric:
case CellType.Unknown:
default:
return cell.ToString();
case CellType.String:
return cell.StringCellValue;
case CellType.Formula:
try
{
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
e.EvaluateInCell(cell);
return cell.ToString();
}
catch
{
return cell.NumericCellValue.ToString();
}
}
} /// <summary>
/// Excel导入
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public DataTable ImportExcelFile(string filePath)
{
HSSFWorkbook hssfworkbook;
#region//初始化信息
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
}
catch (Exception e)
{
throw e;
}
#endregion ISheet sheet = hssfworkbook.GetSheetAt();
DataTable table = new DataTable();
IRow headerRow = sheet.GetRow();//第一行为标题行
int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum - ; for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
for (int i = (sheet.FirstRowNum + ); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow(); if (row != null)
{
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = GetCellValue(row.GetCell(j));
}
} table.Rows.Add(dataRow);
}
using (SqlBulkCopy abc = new SqlBulkCopy(SqlConnectionFactory.Connection))
{
abc.BatchSize = table.Rows.Count;
abc.BulkCopyTimeout = ;
abc.DestinationTableName = "ExcelTable";
for (int i = ; i < table.Columns.Count; i++)
{
abc.ColumnMappings.Add(table.Columns[i].ColumnName, i);
}
abc.WriteToServer(table);
}
return table;
} [HttpPost]
public ActionResult TestExcel(FormCollection form)
{
HttpPostedFileBase file = Request.Files[];
string path = Server.MapPath("\\Models");
path += "\\" + file.FileName;
file.SaveAs(path);
ImportExcelFile(path);
return View();
}
public string EE()
{
using (SqlConnection con = SqlConnectionFactory.Connection)
{
string sql = "select TsetId,TheDate, Tnumber, Tname, Depter, Bdate, Beonduty, GetoffWork, BeondutyTwo, GetoffWorkTwo, Belate, Leaver, Absenceoftime, Total, BText from ExcelTable";
var list = con.Query(sql);
return JsonConvert.SerializeObject(list);
}
}
public ActionResult Detailss()
{
ExcelExprot();
return View();
}
protected void ExcelExprot()
{
string schoolname = "";
//创建Excel文件的对象
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
//添加一个sheet
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
//获取list数据
List<Models.TesModel> listRainInfo = GetAlll();// m_BLL.GetSchoolListAATQ(schoolname);
//给sheet1添加第一行的头部标题
NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow();
row1.CreateCell().SetCellValue("工号");
row1.CreateCell().SetCellValue("姓名");
row1.CreateCell().SetCellValue("所属部门");
row1.CreateCell().SetCellValue("时间");
row1.CreateCell().SetCellValue("上班");
row1.CreateCell().SetCellValue("下班");
row1.CreateCell().SetCellValue("上班");
row1.CreateCell().SetCellValue("下班");
row1.CreateCell().SetCellValue("迟到时间(分钟)");
row1.CreateCell().SetCellValue("早退时间(分钟)");
row1.CreateCell().SetCellValue("缺勤时间(分钟)");
row1.CreateCell().SetCellValue("合计");
row1.CreateCell().SetCellValue("备注"); //将数据逐步写入sheet1各个行 年龄>备注
for (int i = ; i < listRainInfo.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + );
rowtemp.CreateCell().SetCellValue(listRainInfo[i].TsetId.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].TheDate.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].Tnumber.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].Tnumber.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].Tname.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].Depter.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].Bdate.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].Beonduty.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].GetoffWork.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].BeondutyTwo.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].Belate.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].Leaver.ToString());
rowtemp.CreateCell().SetCellValue(listRainInfo[i].Absenceoftime.ToString()); }
// 写入到客户端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
ms.Seek(, SeekOrigin.Begin); ms.Flush();
ms.Position = ;
//编辑完后 通过response输出
Response.Clear();
Response.Buffer = true;
Response.Charset = "UTF8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/msexcel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("考勤明细.xls"));
Response.BinaryWrite(ms.ToArray());
Response.Flush();
Response.End();
}
private List<Models.TesModel> GetAlll()
{
List<Models.TesModel> list = new List<Models.TesModel>();
string sql = "select TsetId,TheDate, Tnumber, Tname, Depter, Bdate, Beonduty, GetoffWork, BeondutyTwo, GetoffWorkTwo, Belate, Leaver, Absenceoftime from ExcelTable";
SqlConnection DBper = SqlConnectionFactory.Connection;
var oo = DBper.Query(sql);
var json = JsonConvert.SerializeObject(oo);
list = JsonConvert.DeserializeObject<List<Models.TesModel>>(json);
return list;
}

控制器

@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<div>
<form action="/Home/TestExcel" enctype="multipart/form-data" method="post">
<text>选择:(工作表名“Sheet1”)</text>
<input name="file" type="file" id="file" />
<input type="submit" name="Upload" value="导入" />
</form>
<input id="Button1" type="button" value="导出" onclick="location.href='/Home/Detailss'" />
<table>
<thead>
<tr>
<th>工号</th>
<th>姓名</th>
<th>所属部分</th>
<th>时间</th>
<th>上班</th>
<th>下班</th>
<th>上班</th>
<th>下班</th>
<th>迟到时间(分钟)</th>
<th>早退时间(分钟)</th>
<th>缺勤时间(分钟)</th>
<th>合计(分钟)</th>
<th>备注</th>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>
</div>
<script>
$(document).ready(function () {
$.ajax({
url: '/Home/EE',
dataType: 'json',
type: 'get',
success: function (data) {
$(data).each(function () {
var tr = '<tr>'
+ '<td>' + this.TsetId + '</td>'
+ '<td>' + this.TheDate+'</td>'
+ '<td>' + this.Tnumber + '</td>'
+ '<td>' + this.Tname + '</td>'
+ '<td>' + this.Depter + '</td>'
+ '<td>' + this.Bdate + '</td>'
+ '<td>' + this.Beonduty + '</td>'
+ '<td>' + this.GetoffWork + '</td>'
+ '<td>' + this.BeondutyTwo + '</td>'
+ '<td>' + this.GetoffWorkTwo + '</td>'
+ '<td>' + this.Belate + '</td>'
+ '<td>' + this.Leaver + '</td>'
+ '<td>' + this.Absenceoftime + '</td>'
+ '<td>' + this.Total + '</td>'
+ '<td>' + this.BText + '</td>'
+ '</tr>';
$("#tb").append(tr);
})
}
})
})
</script>
</body> </html>

View

 public class SqlConnectionFactory
{
private static readonly string ConnString =
ConfigurationManager.ConnectionStrings["DapperDemo"].ConnectionString; private static object _obj = new object(); public static SqlConnection Connection
{
get
{
SqlConnection connection = null; if (connection == null)
{
lock (_obj)
{
if (connection == null)
{
connection = new SqlConnection(ConnString);
}
}
}
connection.Open();
return connection;
}
}
}

帮助类

/// <summary>
/// 实体转换辅助类
/// </summary>
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; // 检查DataTable是否包含此列 if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue; object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}

实体转换辅助类

Excel接口导出,导入数据库(.Net)的更多相关文章

  1. atitit.sql server2008导出导入数据库大的表格文件... oracle mysql

    atitit.sql server2008导出导入数据库大的表格文件... 1. 超过80M的文件是不能在查询分析器中执行的 1 2. Oracle ,mysql大的文件导入 1 2.1. 使用sql ...

  2. Java实现Excel数据批量导入数据库

    Java实现Excel数据批量导入数据库 概述: 这个小工具类是工作中的一个小插曲哦,因为提数的时候需要跨数据库导数... 有的是需要从oracle导入mysql ,有的是从mysql导入oracle ...

  3. 将Excel中数据导入数据库(三)

    上篇文章将Excel中数据导入数据库时,将从Excel读入的数据均转换成了数据库相应字段的类型,其实这是没有必要的,因为对于数据库各种类型的插入,均可以字符串格式插入.比如表WQ_SWMSAR_A字段 ...

  4. 将Excel中数据导入数据库(二)

    在上篇文章中介绍到将Excel中数据导入到数据库中,但上篇文章例子只出现了nvachar类型,且数据量很小.今天碰到将Excel中数据导入数据库中的Excel有6419行,其中每行均有48个字段,有i ...

  5. 将Excel中数据导入数据库(一)

    在工作中经常要将Excel中数据导入数据库,这里介绍一种方法. 假如Excel中的数据如下: 数据库建表如下: 其中Id为自增字段: Excel中数据导入数据库帮助类如下: using System; ...

  6. mysql进阶(十三)命令行导出导入数据库

    MySQL命令行导出导入数据库 MySQL命令行导出数据库: 1,进入MySQL目录下的bin文件夹:cd MySQL中到bin文件夹的目录 如我输入的命令行:cd D:\Program Files\ ...

  7. 第二百九十节,MySQL数据库-MySQL命令行导出导入数据库,数据库备份还原

    MySQL命令行导出导入数据库,数据库备份还原 MySQL命令行导出数据库:1,进入MySQL目录下的bin文件夹:cd MySQL中到bin文件夹的目录如我输入的命令行:cd C:\Program ...

  8. MySQL可视化软件Work Bench导出导入数据库

    首先打开你的work bench,输入你的密码进入主页面 A:导入数据库 在Schemas空白处右键选择Create~:建立一个数据库,然后就可以导入你的sql文件了 File-->Open S ...

  9. mysql命令导出导入数据库

    命令导出数据库: mysqldump -h[主机所在IP] -u[用户名] -p [要导出的数据库]>[导出的路径//[文件名].sql] 命令导入数据库: 1>首先,我们应该在cmd中进 ...

  10. jsp上传excel文件并导入数据库

    1,excel文件的上传 需要借助jar包:commons-fileupload-1.2.1.jar以及commons-io-1.3.2.jar 前端的html文件 <form id=" ...

随机推荐

  1. 判断dom原始是否在可视区域内

    isElementInViewport (el, offset = 0) { const box = el.getBoundingClientRect(), top = (box.top >= ...

  2. python unittest+parameterized,单元测试框架+参数化

    总要写新的自动化测试模块,在这里把demo记录下来,后面方便自己直接复制粘贴 from nose_parameterized import parameterized import unittest ...

  3. 原来python如此神奇

    一.优缺点分析 1.缺点: ① 数学问题的生成中只考虑了消除乘除法加括号的无效情况(例如3*(4+5)或(6*5)/2这样的计算),但没有去掉加减法加括号的无效情况(例如(4+(7+8))或(3-(2 ...

  4. 略学扩展Eculid算法

    扩展 Euclid 算法 Euclid 算法 辗转相除法 计算两个数最大公因数 \(\text{gcd}(a,\,b) = \text{gcd}(b,\,a\%b)\) exEuclid 算法 裴蜀定 ...

  5. JMeter 压测Server Agent无法监控资源问题,PerfMon Metrics Collector报Waiting for sample,Error loading results file - see file log, Can't accept UDP connections java.net.BindException: Address already in use 各种疑难杂症

    如何安装插件此博主已经说得很详细了. https://www.cnblogs.com/saryli/p/6596647.html 但是需注意几点: 1.修改默认端口,这样可以避免掉一个问题.Serve ...

  6. Julia初学备忘

    println("hello!") println("hello!") print("hello!") print("hello! ...

  7. javascript中字符串对象常用的方法和属性

    前言 字符串是一种非常重要的数据类型,在Java等面向对象编程语言中,它代表对象类型,而在javascript中它却是一种基本数据类型,在开发的领域中,我们经常会碰到,无论是前端还是后台.比如后台验证 ...

  8. .net core 3.0 Signalr - 04 使用Redis做底板来支持横向扩展

    在实际的系统中,可能需要多台机器部署;然而,Signalr的连接信息是跟站点走的,举个例子 推送系统部署了A.B两个服务器,张三访问A服务器,李四访问B服务器,当张三通过A服务器向李四推送的时候,A服 ...

  9. ThinkPHP5 支付宝 电脑与手机支付扩展库

    ThinkPHP5 电脑与手机支付扩展库(2017年9月18日) 使用说明 在默认配置情况下,将文件夹拷贝到根目录即可, 其中extend目录为支付扩展目录, application\extra\al ...

  10. Linux 下复制整个文件夹的命令

    在 Linux 下复制整个文件夹,包括它的子文件夹及其隐藏文件的方法是: cp -r /etc/skel /home/user 或者 mkdir /home/<new_user> cp - ...