效果图
数据库代码
create database CardManage
use CardManage
create table CardManage
(
ID int identity(1,1) primary key,
userDep nvarchar(10)not null,
userName nvarchar(5)not null,
userTel varchar(11)not null,
carNum nvarchar(20)not null,
fixedCarport nvarchar(20)null,
)
insert CardManage values('研发部','小明','','洒B13580','博士二二二二')
insert CardManage values('研发部','小仝','','洒B13580','博士二二二二')
insert CardManage values('酱油部','小华','','洒B13580','博士二二二二') truncate table CardManage
select*from CardManage --第二个表不清楚字段 和名字 我看文档那里有猜的
-- 确定再加上去
create table projectManage
(
ID int identity primary key not null,
projectName nvarchar(20)not null,
manager_1 nvarchar(10) not null,
manager_2 nvarchar(10) not null,
monitor nvarchar(10) not null,
isFire varchar(2) null ,
startTime datetime not null,
endTime datetime not null,
manager_1tel nvarchar(11) not null,
manager_1company nvarchar(20) not null,
manager_2tel nvarchar(11) not null,
manager_2company nvarchar(20) not null,
monitortel nvarchar(11) not null,
monitorcompany nvarchar(20) not null
)
select *from projectManage
insert projectManage values('装机','小明','大明','工程监理','是','1990-9-9','2000-9-9','','','','','','') create proc a
as
truncate table CardManage
go

车辆管理视图代码

@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Scripts/eastui/themes/icon.css" rel="stylesheet" />
<link href="~/Scripts/eastui/themes/default/easyui.css" rel="stylesheet" />
<script src="~/Scripts/eastui/jquery.min.js"></script>
<script src="~/Scripts/eastui/jquery.easyui.min.js"></script>
<script type="text/javascript">
$(function () {
f();
})
function f() {
$('#carportList').datagrid({
url: '../Che/select',//控制器/方法
pagination: true,
pageSize: 10, //每页记录数
pageNumber: 1, //默认显示第几页
pageList: [10, 15, 20], //分页记录数数组
//singleSelect: true,
rownumbers: true,
//toolbar: "#toolbar",
idField: 'ID',
frozenColumns: [[
{ field: 'ck', checkbox: true },
//{ title: '全选', field: 'EmpID', width: 80, sortable: true }
]],
toolbar: [{
id: 'btnadd',
text: '添加',
iconCls: 'icon-add',
handler: function () {
$('#add_name').val(null);//清空文本框
$('#add_tel').val(null);
$('#add_carNum').val(null);
$('#add_dep').val(null);
$('#add_fixedCarport').val(function () {
var a = null
}); $('#addCarWin').window('open'); }
},
{
text: '删除',
id: 'btn_admin_del',
iconCls: 'icon-cut',
handler: function () {
del();
}, },
{
text: 'excel导出',
id: 'excelout', handler: function () {
window.open('/Che/ExportExcel');
}
},
{
text: 'npoi导出',
id: 'npoiout',
handler: function () {
window.open('/Che/npoiout')
}
}
],
columns: [[
{ field: 'userName', title: '姓名', width: 80, align: 'center' },
{ field: 'userTel', title: '联系电话', width: 100, align: 'center' },
{ field: 'carNum', title: '车牌号码', width: 100, align: 'center' },
{ field: 'userDep', title: '部门', width: 100, align: 'center' },
{ field: 'fixedCarport', title: '固定车位', width: 150, align: 'center' },
{
field: 'operation', width: 100, title: '操作', align: 'center', formatter: function (value, row, index) {
return "<input id='delCarport' href='javascript:void(0)' type='button' value='删除' onclick='Detailed();' \>"
}
} ]]
});
var p = $('#carportList').datagrid('getPager');
$(p).pagination({
beforePageText: '第',//页数文本框前显示的汉字
afterPageText: '页 共 {pages} 页',
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录'
});
// 初始化添加车位信息窗口
$("#addCarWin").window({
title: '添加车位信息',
iconCls: 'icon-add',
width: 'auto',
height: 'auto',
top: 100,
modal: true,
shadow: false,
closed: true,
maximizable: false,
minimizable: false,
resizable: false,
draggable: false
}); }
//添加
function save() {
$('#fm_add').form("submit", {
url: '/Che/insert',
onSubmit: function () {
return $(this).form("validate"); //提交前验证
},
success: function (result) {
if (result == "1") {
$('#addCarWin').dialog('close');
$.messager.alert("提示", "保存成功")
$('#carportList').datagrid('load', {})
}
else {
$.messager.alert("提示", "失败");
}
}
})
}
//搜索
function sele() {
var name = $('#s_name').val();
var carnum = $('#s_carNum').val();
var scar = $('#s_carport').val();
$('#carportList').datagrid('load', {
name: name,
carnum: carnum,
scar: scar
});
};
//删除
function Detailed() {
var row = $('#carportList').datagrid('getSelected');
var ID = row.ID;
var userName = row.userName;
$.messager.confirm('提示', '是否删除' + row.userName + '相关信息?', function (r) {
if (!r) {
return;
}
$.ajax({
type: 'post',
url: "/Che/del",
data: { id: ID },
success: function (msg) {
if (msg.IsSuccess) {
$.messager.alert('提示', '删除成功!', 'info', function () {
$('#carportList').datagrid("reload");
$('#carportList').datagrid('clearSelections');
});
}
},
error: function () {
$.messager.alert('错误', '删除失败!');
}
})
})
}
//批量删除
function del() {
var row = $('#carportList').datagrid('getSelected'); var rows = $('#carportList').datagrid('getSelections'); var ids = [];
for (var i = 0; i < rows.length; i++) {
ids.push(rows[i].ID)
}
//alert(ids);
var name = [];
for (var i = 0; i < rows.length; i++) {
name.push(rows[i].userName)
}
names = name.toString();
//alert(ids);
id = ids.toString(); //alert(id);
if (!row) {
$.messager.alert('提示', '请选择要删除的员工');
return;
}
else { $.messager.confirm('提示', '是否删除项目名为“' + names + '”的项目?', function (r) {
if (!r) {
return;
}
$.ajax({
type: "POST",
url: "/Che/delete/",
data: { id: id },
success: function (msg) {
if (msg = "1") {
$.messager.alert('提示', '删除成功!', 'info', function () {
$('#carportList').datagrid("reload");
$('#carportList').datagrid('clearSelections'); });
}
else {
alert("删除失败");
}
},
error: function () {
$.messager.alert('错误', '删除失败!');
}
});
});
} }
$.extend($.fn.validatebox.defaults.rules, {
mobile: {//value值为文本框中的值
validator: function (value) {
var reg = /^1[3|4|5|8|9]\d{9}$/;
return reg.test(value);
},
message: '输入手机号码格式不准确.'
},
CHS: {//只能输入汉字
validator: function (value) {
return /^[\u0391-\uFFE5]+$/.test(value);
},
message: '只能输入汉字'
},
phoneAndMobile: {//电话号码或手机号码
validator: function (value) {
return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value) || /^(13|15|18)\d{9}$/i.test(value);
},
message: '电话号码或手机号码格式不正确'
},
carNo: { //验证车牌
validator: function (value) {
return /^[\u4E00-\u9FA5][\da-zA-Z]{6}$/.test(value);
},
message: '车牌号码无效(例:粤B12350)'
},
test: {
validator: function (value) {
var a = value
if (a == "") {
a = null;
}
return a
}
} }) //利用表单导入EXCEL
function excel() {
$("#upexcel").form("submit", {
url: '/Che/upexcel/',
onSubmit: function () {
return $(this).form("validate"); //提交前验证
},
success: function (data) { $.messager.alert('Excel批量用户导入', data, 'info');
$('#carportList').datagrid('load', {})
$('#carportList').datagrid("reload");
}
}
)
} //利用npoi 表单导入excel function nopiexcel() {
$("#npoiexcel").form("submit", {
url: '/Che/npoiload/',
onSubmit: function () {
return $(this).form("validate"); //提交前验证
},
success: function (data) { $.messager.alert('Excel批量用户导入', data, 'info');
$('#carportList').datagrid('load', {})
$('#carportList').datagrid("reload");
}
}
)
} //前端获取路径导入EXCEL这方法已不现实 只能在IE中实现
function OK() { //点击确定按钮的时候
var file = getPath(document.getElementById("FileUpload")); alert(file);
if (file == "") {
$.messager.alert('系统提示', '请选择将要上传的文件!');
document.forms[0].submit();
}
else {
var stuff = file.match(/^(.*)(\.)(.{1,8})$/)[3];
if (stuff != 'xls') {
alert('文件类型不正确,请选择.xls文件!');
document.forms[0].submit();
}
else {
$.ajax({
type: "POST",
url: "/Che/UpLoad",
data: "file=" + file + "",
success: function (result) {
$.messager.alert('系统提示', result + "");
$('#carportList').datagrid("reload");
}
});
}
}
} //判断浏览器路径
function getPath(obj) {
if (obj) {
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
obj.select(); return document.selection.createRange().text;
}
else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
if (obj.files) {
return obj.files.item(0).getAsDataURL();
}
return obj.value;
}
return obj.value;
}
}
</script>
<title>Index</title>
</head>
<body>
<!-- 搜索工具栏 -->
<div class="search">
<label>姓名:<input type="text" id="s_name" /></label>
<label>车牌号:<input type="text" id="s_carNum" /></label>
<label>车位:<input type="text" id="s_carport" /></label>
<a href="javascript:void(0)" id="searchBtn" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'" onclick="sele()">查询</a>
<a href="javascript:void(0)" id="showPlanBtn" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'">查看平面图</a> </div><input id="FileUpload" type="file" name="upload" style="width: 250px; background: White" class="easyui-validatebox" validtype="length[1,100]" />
<input id="Button2" type="button" value="前端验证批量导入" onclick="OK()" /> <form id="upexcel" method="post" enctype="multipart/form-data">
<input id="upload" type="file" name="upload" style="width: 250px; background: White" />
<input id="Button3" type="button" value="上传文件后批量导入" onclick="excel()" />
</form>
<form id="npoiexcel" method="post" enctype="multipart/form-data">
<input id="npoiload" type="file" name="npoiload" style="width: 250px; background: White" />
<input id="Button4" type="button" value="nopi批量导入" onclick="nopiexcel()" />
</form> <!-- 搜索工具栏end --> <table id="carportList"></table> <!-- 添加车位信息窗口 -->
<div id="addCarWin">
<form id="fm_add" method="post" novalidate>
<table class="detailTbl" style="width: 100%;" border="1">
<tbody>
<tr>
<th>姓名:</th>
<td>
<input id="add_name" name="add_name" class="easyui-validatebox" type="text" data-options="validType:'CHS' ,required:'true', missingMessage:'姓名不能为空'"/></td>
<th>联系电话:</th>
<td>
<input id="add_tel" name="add_tel" class="easyui-validatebox" type="text" data-options="validType:'phoneAndMobile' ,required:'true', missingMessage:'联系电话不能为空'" "/>
</td>
</tr>
<tr>
<th>车牌号码:</th>
<td colspan="3">
<input id="add_carNum" name="add_carNum" class="easyui-validatebox" type="text" data-options="validType:'carNo' ,required:'true', missingMessage:'车牌不能为空'" />
</td>
</tr>
<tr> <th>部门:</th>
<td>
<input id="add_dep" name="add_dep" class="easyui-validatebox" type="text" data-options="required:'true', missingMessage:'部门不能为空'"/></td>
<th>固定车位:</th>
<td>
<input id="add_fixedCarport" name="add_fixedCarport" class="easyui-validatebox" data-options="validType:'test'" type="text" /></td>
</tr>
<tr>
<td colspan="4" style="text-align:right" >
<a id="add" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="save()">确定</a>
<a id="close" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'"onclick="javascript:$('#addCarWin').dialog('close');"">取消</a>
</td>
</tr>
</tbody>
</table> </form>
</div> <div class="easyui-window" id="planWrap" title="平面图" data-options="closed:true,modal:true,resizable:false,top:0,minimizable:false,maximizable:false,maximized:true,draggable:false">
<img src="themes/images/plan.jpg" alt="平面图" />
</div>
</body>
</html>

工程监控视图代码

@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Scripts/eastui/themes/icon.css" rel="stylesheet" />
<link href="~/Scripts/eastui/themes/default/easyui.css" rel="stylesheet" />
<script src="~/Scripts/eastui/jquery.min.js"></script>
<script src="~/Scripts/eastui/jquery.easyui.min.js"></script>
<title>Index</title>
<script type="text/javascript">
//$(function () {
// $(':radio[name="sex1"]').eq(0).attr("checked", true)
//})
$(function () {
f();
d();
}) window.setInterval(showalert, 3000);
function showalert()
{
var rows = $('#a').datagrid('getData');
var a = rows.total;
//alert(a)
$.ajax({
type: "POST",
url: '/Project/ss/',
success: function (result) { if (a!= result)
{
//alert(result)
$('#a').datagrid("reload");
}
}
}) } function f() {
$('#a').datagrid({
url: '../Project/sa',//控制器/方法
pagination: true,
pageSize:10, //每页记录数
pageNumber: 1, //默认显示第几页
pageList: [10,15,20], //分页记录数数组
//singleSelect: true,
rownumbers: true,
//toolbar: "#toolbar",
idField: 'ID',
frozenColumns: [[
{ field: 'ck', checkbox: true },
//{ title: '全选', field: 'EmpID', width: 80, sortable: true }
]],
columns:
[[
{ field: 'projectName', title: '项目名称', width:120, align: 'center' },
{ field: 'isFire', title: '是否动火作业', width:80, align: 'center' },
{
field: 'startTime', title: '施工开始时间', width:100, align: 'center', formatter: function ChangeDateFormat(val) {
if (val != null) {
var date = new Date(parseInt(val.replace("/Date(", "").replace(")/", ""), 10));
//月份为0-11,所以+1,月份小于10时补个0
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "-" + month + "-" + currentDate;
} return "";
},
},
{
field: 'endTime', title: '施工结束时间', width:100, align: 'center', formatter: function ChangeDateFormat(val) {
if (val != null) {
var date = new Date(parseInt(val.replace("/Date(", "").replace(")/", ""), 10));
//月份为0-11,所以+1,月份小于10时补个0
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "-" + month + "-" + currentDate;
} return "";
},
},
{ field: 'manager_1', title: '项目主管(甲方)', width:100, align: 'center' },
{ field: 'manager_2', title: '项目主管(乙方)', width:100, align: 'center' },
{ field: 'monitor', title: '工程监理', width:100, align: 'center' },
//{
// field: 'operation', width: 100, title: '操作', align: 'center', formatter: function (value, row, index) {
// return "<a id='delProjectBtn' onclick='delProject(\"" + value + "\");' class='behindBut'>删除</a> <a id='editProjectBtn' onclick='editProject(\"" + value + "\");' class='behindBut'>编辑</a>";
// }
//}
]], toolbar: [
{
id: 'btnadd',
text: '添加',
iconCls: 'icon-add',
handler: function () { //添加车位信息方法
$('#addProjectWin').window('open');
}
}, {
text: '删除',
id: 'btn_admin_del',
iconCls: 'icon-cut',
handler: function () {
del();
}
}, '-', {
text: '修改',
id: 'btn_admin_edit',
iconCls: 'icon-save',
handler: function ()
{ var rows = $('#a').datagrid('getSelections');
var a = rows.length;
if (a == 0) {
alert("需要要选择一条数据")
}
if (a == 1) {
var row = $('#a').datagrid('getSelected');
$('#editProjectWin').window('open');
var name = row.projectName;
var is = row.isFire; if (is == "是") {
$('#r1').attr('checked', 'true')
}
if (is == '否') {
$('#r2').attr('checked', 'true')
}
var id = row.ID;
var m1 = row.manager_1;
var m1t = row.manager_1tel;
var m1c = row.manager_1company;
var m2 = row.manager_2;
var m2t = row.manager_2tel
var m2c = row.manager_2company;
var mo=row.monitor;
var mot=row.monitortel;
var moc = row.monitorcompany;
var datatime1 = row.startTime;
var datatime2 = row.endTime; var date1 = new Date(parseInt(datatime2.replace("/Date(", "").replace(")/", ""), 10)); //月份为0-11,所以+1,月份小于10时补个0
var month1 = date1.getMonth() + 1 < 10 ? "0" + (date1.getMonth() + 1) : date1.getMonth() + 1;
var currentDate1 = date1.getDate() < 10 ? "0" + date1.getDate() : date1.getDate();
var dt2 = month1 + "/" + currentDate1 + "/" + date1.getFullYear() var date = new Date(parseInt(datatime1.replace("/Date(", "").replace(")/", ""), 10)); //月份为0-11,所以+1,月份小于10时补个0
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
var dt1 = month + "/" + currentDate + "/" + date.getFullYear() dt1.toString(); $("#mod_projectName").attr("value", name);// 填充内容
$("#id").attr("value", id) $('#dt1').datebox('setValue', dt1);
$('#dt2').datebox('setValue', dt2);
$("#m1").attr("value", m1)
$("#m1t").attr("value", m1t)
$("#m1c").attr("value", m1c)
$("#m2").attr("value", m2)
$("#m2t").attr("value", m2t)
$("#m2c").attr("value", m2c)
$("#mo").attr("value", mo)
$("#mot").attr("value", mot)
$("#moc").attr("value", moc)
} if(a>1){
alert("只能选择一条数据")
$('#a').datagrid('clearSelections');
}
}
},
{
text: 'excel导出',
id: 'excelout', handler: function () {
window.open('/Project/ExportExcel');
}
},
{
text: 'nopi导出excel',
id: 'nopi',
handler: function () {
window.open('/Project/nopi');
}
} ]
}); var p = $('#a').datagrid('getPager');
$(p).pagination({
beforePageText: '第',//页数文本框前显示的汉字
afterPageText: '页 共 {pages} 页',
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录'
});
$("#addProjectWin").window({
title: '添加工程监管',
iconCls: 'icon-add',
width: 'auto',
height: 'auto',
top: 100,
modal: true,
shadow: false,
closed: true,
maximizable: false,
minimizable: false,
resizable: false,
draggable: true
});
$("#editProjectWin").window({
title: '编辑工程监管',
iconCls: 'icon-edit',
width: 'auto',
height: 'auto',
top: 100,
modal: true,
shadow: false,
closed: true,
maximizable: false,
minimizable: false,
resizable: false,
draggable: true
});
}; //利用表单导入EXCEL
function excel() {
$("#upexcel").form("submit", {
url: '/Project/upexcel/',
onSubmit: function () {
return $(this).form("validate"); //提交前验证
},
success: function (data) { $.messager.alert('Excel批量用户导入', data, 'info');
$('#a').datagrid('load', {})
$('#a').datagrid("reload");
}
}
)
}
//利用nopi表单提交后导入excel
function npoiexcel() {
$("#npoiload").form("submit", {
url: '/Project/npoiload/',
onSubmit: function () {
return $(this).form("validate"); //提交前验证
},
success: function (data) { $.messager.alert('Excel批量用户导入', data, 'info');
$('#a').datagrid('load', {})
$('#a').datagrid("reload");
}
}
)
}
//搜索
function so() {
var name = $('#s_name').val();
$('#a').datagrid('load', {
name:name
}); }
//批量删除
function del() {
var row = $('#a').datagrid('getSelected'); var rows = $('#a').datagrid('getSelections');
var ids = [];
for (var i = 0; i < rows.length; i++) {
ids.push(rows[i].ID)
}
var name = [];
for (var i = 0; i < rows.length; i++) {
name.push(rows[i].projectName)
}
names = name.toString();
//alert(ids);
id = ids.toString(); //alert(id);
if (!row) {
$.messager.alert('提示', '请选择要删除的员工');
return;
}
else { $.messager.confirm('提示', '是否删除项目名为“' + names + '”的项目?', function (r) {
if (!r) {
return;
}
$.ajax({
type: "POST",
url: "/Project/del/",
data: { id: id },
success: function (msg) {
if (msg = "1") {
$.messager.alert('提示', '删除成功!', 'info', function () {
$('#a').datagrid("reload");
$('#a').datagrid('clearSelections'); });
}
else {
alert("删除失败");
}
},
error: function () {
$.messager.alert('错误', '删除失败!');
}
});
});
} } //添加
function saveUser() {
$("#fm_add_admin").form("submit", {
url: '/Project/add/', //使用参数
onSubmit: function () {
return $(this).form("validate"); //提交前验证
},
success: function (result) {
if (result == "1") { $.messager.alert("提示", "保存成功")
$('#addProjectWin').window('close'); $('#a').datagrid('load', {}) }
else {
$.messager.alert("提示", "失败");
}
}
});
}
function d() {
$('#dd').datebox({
required: true
});
$('#dd2').datebox({
required: true
});
}
function dsosuo() {
var d1 = $('#dd').datebox('getValue');
var d2 = $('#dd2').datebox('getValue');
//alert(d2);
var startdate = new Date(d1.replace(/-/g, "/"));
var enddate = new Date(d2.replace(/-/g, "/"));
if (d1 > d2) {
alert("开始日期不能大于结束日期");
}
else {
$('#a').datagrid('load', {
d1: d1,
d2: d2, });
} //})
} //修改方法
function editUser() {
var row = $('#a').datagrid('getSelected');
var id = row.EmpID;
$('#fm_modify_admin').form('submit', {
url: '/Project/edit/',
onSubmit: function () {
return $(this).form('validate');
},
success: function (result) {
if (result == "1") {
$('#dlg_edit_admin').dialog('close');
$.messager.alert("提示", "修改成功")
$('#editProjectWin').window('close');
$("#a").datagrid("reload"); }
else {
$.messager.alert("提示", result);
}
}
});
} $.extend($.fn.validatebox.defaults.rules, {
mobile: {//value值为文本框中的值
validator: function (value) {
var reg = /^1[3|4|5|8|9]\d{9}$/;
return reg.test(value);
},
message: '输入手机号码格式不准确.'
},
CHS: {//只能输入汉字
validator: function (value) {
return /^[\u0391-\uFFE5]+$/.test(value);
},
message: '只能输入汉字'
},
phoneAndMobile: {//电话号码或手机号码
validator: function (value) {
return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value) || /^(13|15|18)\d{9}$/i.test(value);
},
message: '电话号码或手机号码格式不正确'
},
carNo: { //验证车牌
validator: function (value) {
return /^[\u4E00-\u9FA5][\da-zA-Z]{6}$/.test(value);
},
message: '车牌号码无效(例:粤B12350)'
} }) </script>
</head>
<body>
<div class="search">
<label>项目名称:<input type="text" id="s_name" /></label>
<a href="javascript:void(0)" id="searchBtn" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'" onclick="so()">查询</a>

<input id="dd" type="text" editable="false" missingMessage="日期必须填写">

<input id="dd2" type="text" editable="false" missingMessage="日期必须填写">
<input id="Button1" type="button" value="搜索" onclick="dsosuo()" />
<form id="upexcel" method="post" enctype="multipart/form-data">
<input id="upload" type="file" name="upload" style="width: 250px; background: White" />
<input id="Button3" type="button" value="上传文件后批量导入" onclick="excel()" />
</form>
<form id="npoiload" method="post" enctype="multipart/form-data">
<input id="nopiupload" type="file" name="npoiload" style="width: 250px; background: White" />
<input id="Button4" type="button" value="npoi批量导入" onclick="npoiexcel()" />
</form> </div> <table id="a"></table>
<div id="addProjectWin">
<form id="fm_add_admin" method="post" novalidate>
<table class="detailTbl" style="width: 100%;" border="1"> <tbody>
<tr>
<th>项目名称:</th>
<td>
<input id="add_projectName" name="projectName" class="easyui-validatebox" data-options="required:'true', missingMessage:'项目名不能为空'"/></td>
<th>是否动火作业:</th>
<td>
<label>
<input type="radio" name="isFire" value="是" checked="checked">是</label>
<label>
<input type="radio" name="isFire" value="否" />否</label>
</td>
</tr>
<tr>
<th>施工时间:</th>
<td colspan="3">
<input type="text" class="easyui-datebox" name="startTime" editable="false" data-options="required:'true',missingMessage:'开始时间不能为空'" >
@* <input class="easyui-datetimebox" type="text" name="startTime" data-options="width:154" />*@至
@* <input class="easyui-datetimebox" type="text" name="endTime " data-options="width:154" />*@
<input type="text" class="easyui-datebox" name="endTime" editable="false" data-options="required:'true',missingMessage:'截止时间不能为空'" >
</td>
</tr>
<tr>
<th>相关人员:</th>
<td colspan="3">
<table>
<thead>
<tr>
<th>身份</th>
<th>姓名</th>
<th>电话</th>
<th>公司</th>
</tr>
</thead>
<tbody>
<tr>
<td>项目主管(甲方)</td>
<td>
<input type="text" name="manager_1" class="easyui-validatebox" data-options="validType:'CHS' ,required:'true', missingMessage:'姓名不能为空'"/></td>
<td>
<input type="text" name="manager_1tel" class="easyui-validatebox" data-options="validType:'phoneAndMobile' ,required:'true', missingMessage:'联系电话不能为空'"/></td>
<td>
<input type="text" name="manager_1company" class="easyui-validatebox" data-options="required:'true', missingMessage:'公司不能为空'"/></td>
</tr>
<tr>
<td>项目主管(乙方)</td>
<td>
<input type="text" name="manager_2" class="easyui-validatebox" data-options="validType:'CHS' ,required:'true', missingMessage:'姓名不能为空'"/></td>
<td>
<input type="text" name="manager_2tel" class="easyui-validatebox" data-options="validType:'phoneAndMobile' ,required:'true', missingMessage:'联系电话不能为空'"/></td>
<td>
<input type="text" name="manager_2company" class="easyui-validatebox" data-options="required:'true', missingMessage:'公司不能为空'" /></td>
</tr>
<tr>
<td>工程监理</td>
<td>
<input type="text" name="monitor" class="easyui-validatebox" data-options="validType:'CHS' ,required:'true', missingMessage:'姓名不能为空'"/></td>
<td>
<input type="text" name="monitortel" class="easyui-validatebox" data-options="validType:'phoneAndMobile' ,required:'true', missingMessage:'联系电话不能为空'"/></td>
<td>
<input type="text" name="monitorcompany" class="easyui-validatebox" data-options="required:'true', missingMessage:'公司不能为空'"/></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody> </table>
</form>
<div id="dlg_add_admin_buttons" style="text-align: left">
<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="saveUser()">添 加</a>
<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" onclick="javascript:$('#addProjectWin').window('close');">取 消</a>
</div>
</div> <div id="editProjectWin">
<form id="fm_modify_admin" method="post" novalidate>
<table class="detailTbl" style="width: 100%;" border="1"> <tbody>
<tr> <th>
<input id="id" name="ID" style="display:none" />
项目名称:</th>
<td>
<input id="mod_projectName" name="projectName" class="easyui-validatebox" type="text" data-options="required:'true'"/></td>
<th>是否动火作业:</th>
<td>
<label>
<input type="radio" id="r1" name="isFire" value="是"/>是</label>
<label>
<input type="radio" id="r2" name="isFire" value="否" />否</label>
</td>
</tr>
<tr>
<th>施工时间:</th>
<td colspan="3">
<input id="dt1" type="text" editable="false" class="easyui-datebox" name="startTime" data-options="required:'true',missingMessage:'开始时间不能为空'">
@* <input class="easyui-datetimebox" type="text" name="startTime" data-options="width:154" />*@至
@* <input class="easyui-datetimebox" type="text" name="endTime " data-options="width:154" />*@
<input id="dt2" type="text" editable="false" class="easyui-datebox" name="endTime" data-options="required:'true',missingMessage:'截止时间不能为空'" >
</td>
</tr>
<tr>
<th>相关人员:</th>
<td colspan="3">
<table>
<thead>
<tr>
<th>身份</th>
<th>姓名</th>
<th>电话</th>
<th>公司</th>
</tr>
</thead>
<tbody>
<tr>
<td>项目主管(甲方)</td>
<td>
<input id="m1" type="text" name="manager_1" class="easyui-validatebox" data-options="validType:'CHS' ,required:'true', missingMessage:'姓名不能为空'"/></td>
<td>
<input id="m1t" type="text" name="manager_1tel" class="easyui-validatebox" data-options="validType:'phoneAndMobile' ,required:'true', missingMessage:'联系电话不能为空'"/></td>
<td>
<input id="m1c" type="text" name="manager_1company" class="easyui-validatebox" data-options="required:'true', missingMessage:'公司不能为空'"/></td>
</tr>
<tr>
<td>项目主管(乙方)</td>
<td>
<input id="m2" type="text" name="manager_2" class="easyui-validatebox" data-options="validType:'CHS' ,required:'true', missingMessage:'姓名不能为空'" /></td>
<td>
<input id="m2t" type="text" name="manager_2tel" class="easyui-validatebox" data-options="validType:'phoneAndMobile' ,required:'true', missingMessage:'联系电话不能为空'"/></td>
<td>
<input id="m2c" type="text" name="manager_2company" class="easyui-validatebox" data-options="required:'true', missingMessage:'公司不能为空'" /></td>
</tr>
<tr>
<td>工程监理</td>
<td>
<input id="mo" type="text" name="monitor" class="easyui-validatebox" data-options="validType:'CHS' ,required:'true', missingMessage:'姓名不能为空'"/></td>
<td>
<input id="mot" type="text" name="monitortel" class="easyui-validatebox" data-options="validType:'phoneAndMobile' ,required:'true', missingMessage:'联系电话不能为空'"/></td>
<td>
<input id="moc" type="text" name="monitorcompany" class="easyui-validatebox" data-options="required:'true', missingMessage:'公司不能为空'"/></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody> </table>
</form>
<div id="dlg_modify_admin_buttons" style="text-align: left">
<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="editUser()">修改</a>
<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" onclick="javascript:$('#editProjectWin').window('close');">取 消</a>
</div>
</div>
<div> </div>
</body>
</html>

分页类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace CarportManage.Models
{
public class datagrid
{ public int total { get; set; }
public object rows { get; set; } }
}

车辆管理控制器

using CarportManage.Models;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc; namespace CarportManage.Controllers
{
public class CheController : Controller
{
//
// GET: /Che/
CardManageEntities3 db = new CardManageEntities3();
public ActionResult Index()
{
return View();
}
//添加
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult insert(FormCollection from)
{
int success;
try
{ CardManage t = new CardManage();
t.userName = from["add_name"];
t.userTel = from["add_tel"];
t.carNum = from["add_carNum"];
t.userDep = from["add_dep"];
t.fixedCarport = from["add_fixedCarport"];
db.CardManage.Add(t);
db.SaveChanges();
success = ; }
catch (Exception)
{
success = ; }
//new { success = true }
return Content(success.ToString());
} //查询加分页
public ActionResult select(string name, string carnum, string scar)
{
datagrid obj = new datagrid();
int pageSize = Convert.ToInt32(Request["rows"]);
int pageNum = Convert.ToInt32(Request["page"]);
if (name == null && carnum == null && scar == null)
{
var all = from a in db.CardManage select a;
obj.total = all.Count();
obj.rows = all.OrderBy(p => p.ID).Skip(pageSize * (pageNum - )).Take(pageSize);
return Json(obj, JsonRequestBehavior.AllowGet);
}
if (name != null && carnum != null && scar != null)
{
var al = (from c in db.CardManage where c.userName.Contains(name) && c.carNum.Contains(carnum) && c.fixedCarport.Contains(scar) select c).ToList();
obj.total = al.Count();
obj.rows = al.OrderBy(p => p.ID).Skip(pageSize * (pageNum - )).Take(pageSize);
return Json(al, JsonRequestBehavior.AllowGet);
}
else
{
var all = from a in db.CardManage select a;
obj.total = all.Count();
obj.rows = all.OrderBy(p => p.ID).Skip(pageSize * (pageNum - )).Take(pageSize); } return Json(obj);
}
//单条删除
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult del(string id)
{
CardManage tt = new CardManage() { ID = int.Parse(id) };
db.CardManage.Attach(tt);
db.CardManage.Remove(tt);
db.SaveChanges();
return Json(new { IsSuccess = true, Message = "删除成功" });
}
//批量删除
public ActionResult delete(string id)
{
int success;
try
{
string[] split = id.Split(new char[] { ',' });
for (int i = ; i < split.Count(); i++)
{
CardManage tt = new CardManage() { ID = int.Parse(split[i]) };
db.CardManage.Attach(tt);
db.CardManage.Remove(tt);
db.SaveChanges(); }
var all = from a in db.CardManage select a;
int total = all.Count();
if (total == )
{
////db.a();
}
success = ;
}
catch (Exception)
{ success = ;
} return Content(success.ToString());
}
public ActionResult upexcel(FormCollection from)
{
;
HttpPostedFileBase file = Request.Files["upload"]; string FileName;
string savePath = null;
if (file == null || file.ContentLength <= )
{
//xx不能为空
}
else
{
string filename = Path.GetFileName(file.FileName);
int fileSize = file.ContentLength;//上传文件大小
string fileEx = 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))
{
//格式不对
}
if (fileSize >= Maxsize)
{
//容量不对
}
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads\\excel";//获取基目录
savePath = Path.Combine(path, FileName); //放进去
file.SaveAs(savePath);//保存.
}
string result = string.Empty;
try
{
CardManage cm = new CardManage(); string strConn;
//strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + file + "; " + "Extended Properties=Excel 8.0;";
strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", savePath);
//strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", file);
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [$A1:R65536]", strConn);
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "ExcelInfo");
System.Data.DataTable tab = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
// ...用foreach把tab中数据添加到数据库 省略了如果是多表插入,可以调用存储过程.呵呵
int rowsnum = tab.Rows.Count;
if (rowsnum == )
{
Response.Write("<script>alert('Excel表为空表,无数据!')</script>"); //当Excel表为空时,对用户进行提示
}
// ...用foreach把tab中数据添加到数据库 省略了如果是多表插入,可以调用存储过程.呵呵
DataRow[] dr = tab.Select();
for (int i = ; i < dr.Length; i++)
{ cm.userName = dr[i]["姓名"].ToString();
cm.userTel = dr[i]["联系电话"].ToString();
cm.userDep = dr[i]["车牌号码"].ToString();
cm.carNum = dr[i]["部门"].ToString();
cm.fixedCarport = dr[i]["固定车位"].ToString(); // excel列名【名称不能变,否则就会出错】
db.CardManage.Add(cm);
db.SaveChanges();
result = "导入成功!";
} }
catch (Exception)
{ result = "导入失败,请检查EXCEL格式是否错误!";
} JsonResult json = new JsonResult();
json.Data = result;
return json;
}
//excel nopi导出
public ActionResult npoiout()
{
MemoryStream ms = new MemoryStream();
IWorkbook workbook = new HSSFWorkbook();
ISheet st = workbook.CreateSheet("车输管理");
IRow row = st.CreateRow();
row.CreateCell(, CellType.String).SetCellValue("姓名");
row.CreateCell(, CellType.String).SetCellValue("联系电话");
row.CreateCell(, CellType.String).SetCellValue("车牌号码");
row.CreateCell(, CellType.String).SetCellValue("部门");
row.CreateCell(, CellType.String).SetCellValue("固定车位"); int i = ;
foreach (var item in db.CardManage)
{
IRow row1 = st.CreateRow(i);
row1.CreateCell(, CellType.String).SetCellValue(item.userName);
row1.CreateCell(, CellType.String).SetCellValue(item.userTel);
row1.CreateCell(, CellType.String).SetCellValue(item.carNum);
row1.CreateCell(, CellType.String).SetCellValue(item.userDep);
row1.CreateCell(, CellType.String).SetCellValue(item.fixedCarport); i++;
} workbook.Write(ms);
ms.Flush();
ms.Position = ;
return File(ms, "application/vnd.ms-excel", "车辆管理表" + System.DateTime.Now + ".xls");
} //excel导出
public FileResult ExportExcel()
{
CardManage cg = new CardManage();
var a = new StringBuilder();
var b = new List<string> { "姓名", "联系电话", "车牌号码", "部门", "固定车位" };
a.Append("<table border='1' cellspacing='0' cellpadding='0'>");
a.Append("<tr>");
foreach (var item in b)
{
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
}
a.Append("</tr>");
int count = db.CardManage.Count();
List<CardManage> c = new List<CardManage>
{
};
var d = db.CardManage; foreach (var item in d)
{
a.Append("<tr>");
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.userName);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.userTel);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.userDep);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.carNum);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.fixedCarport); a.Append("</tr>");
} a.Append("</table>");
byte[] fileContents = Encoding.Default.GetBytes(a.ToString());
return File(fileContents, "application/ms-excel", "CardManage测试数据.xls"); }
//前端获取路径导入,些方法高端浏览器不能使用,只能在IE上使用
public ActionResult UpLoad(string file)
{
string result = string.Empty;
try
{
CardManage cm = new CardManage(); string strConn;
//strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + file + "; " + "Extended Properties=Excel 8.0;";
strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", file);
//strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", file);
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [$A1:R65536]", strConn);
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "ExcelInfo");
System.Data.DataTable tab = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
// ...用foreach把tab中数据添加到数据库 省略了如果是多表插入,可以调用存储过程.呵呵
int rowsnum = tab.Rows.Count;
if (rowsnum == )
{
Response.Write("<script>alert('Excel表为空表,无数据!')</script>"); //当Excel表为空时,对用户进行提示
}
// ...用foreach把tab中数据添加到数据库 省略了如果是多表插入,可以调用存储过程.呵呵
DataRow[] dr = tab.Select();
for (int i = ; i < dr.Length; i++)
{ cm.userName = dr[i]["姓名"].ToString();
cm.userTel = dr[i]["联系电话"].ToString();
cm.userDep = dr[i]["车牌号码"].ToString();
cm.carNum = dr[i]["部门"].ToString();
cm.fixedCarport = dr[i]["固定车位"].ToString(); // excel列名【名称不能变,否则就会出错】
db.CardManage.Add(cm);
db.SaveChanges();
result = "导入成功!";
} }
catch (Exception)
{ result = "导入失败,请检查EXCEL格式是否错误!";
} JsonResult json = new JsonResult();
json.Data = result;
return json;
} public ActionResult npoiload()
{
string a = "";
try
{
HttpPostedFileBase file = Request.Files["npoiload"];
Stream fs = file.InputStream;
IWorkbook wk = null;
try
{
wk = new XSSFWorkbook(fs);
}
catch (Exception ex)
{
wk = new HSSFWorkbook(fs);
} ISheet st = wk.GetSheetAt();
int rowCount = st.LastRowNum; for (int i = ; i < rowCount; i++)
{ CardManage cm = new CardManage();
cm.userName = st.GetRow(i).GetCell().ToString();
cm.userTel = st.GetRow(i).GetCell().ToString();
cm.carNum = st.GetRow(i).GetCell().ToString();
cm.userDep = st.GetRow(i).GetCell().ToString();
cm.fixedCarport = st.GetRow(i).GetCell().ToString();
db.CardManage.Add(cm);
db.SaveChanges();
a = "导入成功"; }
}
catch (Exception)
{ a = "导入失败,请检查EXCEL格式";
}
return Content(a);
} }
}

工程控件器

using CarportManage.Models;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc; namespace CarportManage.Controllers
{
public class ProjectController : Controller
{
//
// GET: /Project/
CardManageEntities3 db = new CardManageEntities3(); public ActionResult Index()
{
return View();
}
public ActionResult sa(string name, string d1, string d2)
{ datagrid obj = new datagrid();
int pageSize = Convert.ToInt32(Request["rows"]);
int pageNum = Convert.ToInt32(Request["page"]);
if (name != null && name != "")
{
//var al = (from c in db.CardManage where c.userName.Contains(name)).ToList();
//var all = from a in db.projectManage.Where(a => a.projectName == name) select a;
var all = from a in db.projectManage where a.projectName.Contains(name) select a;
obj.total = all.Count();
obj.rows = all.OrderBy(p => p.projectName).Skip(pageSize * (pageNum - )).Take(pageSize); return Json(obj, JsonRequestBehavior.AllowGet);
}
if (d1 != null && d1 != "" && d2 != "" && d2 != null)
{
DateTime d = Convert.ToDateTime(d1);
DateTime dd = Convert.ToDateTime(d2); var all = (from t in db.projectManage where t.startTime >= d && t.endTime <= dd select t); obj.total = all.Count();
obj.rows = all.OrderBy(p => p.projectName).Skip(pageSize * (pageNum - )).Take(pageSize); return Json(obj, JsonRequestBehavior.AllowGet);
}
else
{
var all = from a in db.projectManage select a;
obj.total = all.Count();
obj.rows = all.OrderBy(p => p.ID).Skip(pageSize * (pageNum - )).Take(pageSize); } return Json(obj);
} public ActionResult ss()
{
var all = from a in db.projectManage select a;
int ab = all.Count();
return Content(ab.ToString());
}
//nopi excel导出
public ActionResult nopi()
{ MemoryStream ms = new MemoryStream(); IWorkbook wk = new HSSFWorkbook(); ISheet st = wk.CreateSheet("工程监控");
IRow rw = st.CreateRow();
rw.CreateCell().SetCellValue("项目名称");
rw.CreateCell().SetCellValue("是否动火作业");
rw.CreateCell().SetCellValue("施工开始时间");
rw.CreateCell().SetCellValue("施工结束时间");
rw.CreateCell().SetCellValue("甲方主管");
rw.CreateCell().SetCellValue("甲方主管电话");
rw.CreateCell().SetCellValue("甲方主管公司");
rw.CreateCell().SetCellValue("乙方主管");
rw.CreateCell().SetCellValue("乙方主管电话");
rw.CreateCell().SetCellValue("乙方主管公司");
rw.CreateCell().SetCellValue("工程监控者");
rw.CreateCell().SetCellValue("监控者电话");
rw.CreateCell().SetCellValue("监控者公司"); int a, b, c, d, e, f, g, h, i, j, k, l, m;
a = b = c = d = e = f = g = h = i = j = k = l = m = ; foreach (var item in db.projectManage)
{
st.CreateRow(a++).CreateCell().SetCellValue(item.projectName);
st.GetRow(b++).CreateCell().SetCellValue(item.isFire);
st.GetRow(c++).CreateCell().SetCellValue(item.startTime.ToShortDateString());
st.GetRow(d++).CreateCell().SetCellValue(item.endTime.ToShortDateString());
st.GetRow(e++).CreateCell().SetCellValue(item.manager_1);
st.GetRow(f++).CreateCell().SetCellValue(item.manager_1tel);
st.GetRow(g++).CreateCell().SetCellValue(item.manager_1company);
st.GetRow(h++).CreateCell().SetCellValue(item.manager_2);
st.GetRow(i++).CreateCell().SetCellValue(item.manager_2tel);
st.GetRow(j++).CreateCell().SetCellValue(item.manager_2company);
st.GetRow(k++).CreateCell().SetCellValue(item.monitor);
st.GetRow(l++).CreateCell().SetCellValue(item.monitortel);
st.GetRow(m++).CreateCell().SetCellValue(item.monitorcompany); } wk.Write(ms);
ms.Flush();
ms.Position = ; return File(ms, "application/vnd.ms-excel", "工程监控"+System.DateTime.Now+".xls");
} //excel导出
public FileResult ExportExcel()
{
projectManage cg = new projectManage();
var a = new StringBuilder();
var b = new List<string> { "项目名称", "是否动火作业", "施工开始时间", "施工结束时间", "甲方主管", "甲方主管电话", "甲方主管公司", "乙方主管", "乙方主管电话", "乙方主管公司", "工程监控者", "监控者电话", "监控者公司" };
a.Append("<table border='1' cellspacing='0' cellpadding='0'>");
a.Append("<tr>");
foreach (var item in b)
{
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
}
a.Append("</tr>");
int count = db.projectManage.Count();
List<projectManage> c = new List<projectManage>
{
};
var d = db.projectManage; foreach (var item in d)
{
a.Append("<tr>");
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.projectName);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.isFire);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.startTime);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.endTime);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.manager_1);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.manager_1tel);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.manager_1company);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.manager_2);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.manager_2tel);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.manager_2company);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.monitor);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.monitortel);
a.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item.monitorcompany);
a.Append("</tr>");
} a.Append("</table>");
byte[] fileContents = Encoding.Default.GetBytes(a.ToString());
return File(fileContents, "application/ms-excel", "projectManage测试数据.xls"); }
//excel上传后导入
public ActionResult upexcel()
{ HttpPostedFileBase file = Request.Files["upload"]; string FileName;
string savePath = null;
if (file == null || file.ContentLength <= )
{
//xx不能为空
}
else
{
string filename = Path.GetFileName(file.FileName);
int fileSize = file.ContentLength;//上传文件大小
string fileEx = 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))
{
//格式不对
}
if (fileSize >= Maxsize)
{
//容量不对
}
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads\\excel";//获取基目录
savePath = Path.Combine(path, FileName); //放进去
file.SaveAs(savePath);//保存.
}
string result = string.Empty;
try
{
projectManage pm = new projectManage(); string strConn; strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", savePath);
//strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", file); OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [$A1:R65536]", strConn);
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "ExcelInfo");
System.Data.DataTable tab = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable(); int rowsnum = tab.Rows.Count;
if (rowsnum == )
{
Response.Write("<script>alert('Excel表为空表,无数据!')</script>"); //当Excel表为空时,对用户进行提示
} DataRow[] dr = tab.Select();
for (int i = ; i < dr.Length; i++)
{ pm.projectName = dr[i]["项目名称"].ToString();
pm.isFire = dr[i]["是否动火作业"].ToString(); pm.startTime = Convert.ToDateTime(dr[i]["施工开始时间"]);
pm.endTime = Convert.ToDateTime(dr[i]["施工结束时间"]);
pm.manager_1 = dr[i]["甲方主管"].ToString();
pm.manager_1tel = dr[i]["甲方主管电话"].ToString();
pm.manager_1company = dr[i]["甲方主管公司"].ToString();
pm.manager_2 = dr[i]["乙方主管"].ToString();
pm.manager_2tel = dr[i]["乙方主管电话"].ToString();
pm.manager_2company = dr[i]["乙方主管公司"].ToString();
pm.monitor = dr[i]["工程监控者"].ToString();
pm.monitortel = dr[i]["监控者电话"].ToString();
pm.monitorcompany = dr[i]["监控者公司"].ToString(); // excel列名【名称不能变,否则就会出错】
db.projectManage.Add(pm);
db.SaveChanges();
result = "导入成功!";
}
}
catch (Exception)
{ result = "导入失败,请检查EXCEL格式是否错误!";
} JsonResult json = new JsonResult();
json.Data = result;
return json;
} public ActionResult npoiload()
{ string a = "";
try
{
HttpPostedFileBase file = Request.Files["npoiload"];
Stream fs = file.InputStream;
IWorkbook wk = null;
try
{
wk = new XSSFWorkbook(fs);
}
catch (Exception ex)
{
wk = new HSSFWorkbook(fs);
} ISheet st = wk.GetSheetAt();
int rowCount = st.LastRowNum; for (int i = ; i < rowCount; i++)
{ projectManage pm = new projectManage();
pm.projectName = st.GetRow(i).GetCell().ToString(); ;
pm.isFire = st.GetRow(i).GetCell().ToString();
pm.startTime = Convert.ToDateTime(st.GetRow(i).GetCell().ToString());
pm.endTime = Convert.ToDateTime(st.GetRow(i).GetCell().ToString());
pm.manager_1 = st.GetRow(i).GetCell().ToString();
pm.manager_1tel = st.GetRow(i).GetCell().ToString();
pm.manager_1company = st.GetRow(i).GetCell().ToString();
pm.manager_2 = st.GetRow(i).GetCell().ToString();
pm.manager_2tel = st.GetRow(i).GetCell().ToString();
pm.manager_2company = st.GetRow(i).GetCell().ToString();
pm.monitor = st.GetRow(i).GetCell().ToString();
pm.monitortel = st.GetRow(i).GetCell().ToString();
pm.monitorcompany = st.GetRow(i).GetCell().ToString();
db.projectManage.Add(pm);
db.SaveChanges();
a = "导入成功"; }
}
catch (Exception)
{ a = "导入失败,请检查EXCEL格式";
} return Content(a);
} //添加
//[AcceptVerbs(HttpVerbs.Post)]
public ActionResult add(FormCollection from)
{
//ViewData.Model = from["BookName"];
int success;
try
{
projectManage t = new projectManage();
//;tb_EmpInfoID()
t.projectName = from["projectName"];
t.manager_1 = from["manager_1"];
t.manager_2 = from["manager_2"];
t.monitor = from["monitor"];
t.isFire = from["isFire"];
t.startTime = Convert.ToDateTime(from["startTime"]);
t.endTime = Convert.ToDateTime(from["endTime"]);
t.manager_1tel = from["manager_1tel"];
t.manager_1company = from["manager_1company"];
t.manager_2tel = from["manager_2tel"];
t.manager_2company = from["manager_2company"];
t.monitortel = from["monitortel"];
t.monitorcompany = from["monitorcompany"];
db.projectManage.Add(t);
db.SaveChanges();
success = ; }
catch (Exception)
{
success = ; }
//new { success = true }
return Content(success.ToString());
}
//修改
public ActionResult edit(FormCollection from, projectManage tt)
{
// tb_Emp t = new tb_Emp() { EmpID = id };
// t.EmpName = from["EditEmpName"];
// t.EmpLoginPwd = from["EditEmpLoginPwd"];
int n;
DbEntityEntry<projectManage> entry = db.Entry<projectManage>(tt);
entry.State = System.Data.EntityState.Unchanged;
entry.Property(a => a.ID).IsModified = true;
entry.Property(a => a.projectName).IsModified = true;
entry.Property(a => a.manager_1).IsModified = true;
entry.Property(a => a.manager_2).IsModified = true;
entry.Property(a => a.monitor).IsModified = true;
entry.Property(a => a.isFire).IsModified = true;
entry.Property(a => a.startTime).IsModified = true;
entry.Property(a => a.endTime).IsModified = true;
entry.Property(a => a.manager_1tel).IsModified = true;
entry.Property(a => a.manager_1company).IsModified = true;
entry.Property(a => a.manager_2tel).IsModified = true;
entry.Property(a => a.manager_2company).IsModified = true;
entry.Property(a => a.monitorcompany).IsModified = true;
entry.Property(a => a.monitortel).IsModified = true; db.SaveChanges();
n = ;
return Content(n.ToString()); }
//批量删除
public ActionResult del(string id)
{
int success;
try
{
string[] split = id.Split(new char[] { ',' });
for (int i = ; i < split.Count(); i++)
{
projectManage tt = new projectManage() { ID = int.Parse(split[i]) };
db.projectManage.Attach(tt);
db.projectManage.Remove(tt);
db.SaveChanges(); }
success = ;
}
catch (Exception)
{ success = ;
} return Content(success.ToString());
} }
}

主页视图 控件器就返回一个视图 不写

@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Scripts/eastui/themes/icon.css" rel="stylesheet" />
<link href="~/Scripts/eastui/themes/default/easyui.css" rel="stylesheet" />
<script src="~/Scripts/eastui/jquery.min.js"></script>
<script src="~/Scripts/eastui/jquery.easyui.min.js"></script>
<title>Index</title>
</head>
<body class="easyui-layout">
<div data-options="region:'north',title:'North Title',split:true" style="height:100px;"></div> <div data-options="region:'west',title:'West',split:true" style="width:150px;">
<ul style='list-style-type:none;'>
<li><a style=' text-decoration:none; color:Black' href='/Project/Index' target='I1'>工程监控</a></li> <li><a style=' text-decoration:none; color:Black' href='/Che/Index' target='I1'>车辆管理</a></li>
<li><a style=' text-decoration:none; color:Black' href='/Alert/Index' target='I1'>模拟</a></li>
<li><a href="/Alert/Index">模拟</a></li>
</ul>
</div>
<div data-options="region:'center',title:'center title'" style="padding:0px;background:#eee;">
<iframe id="I1" name="I1" style="width:100%; height:100%;border:0px solid #ffd800"></iframe>
</div>
</body> </html>

asp.net mvc4 easyui datagrid 增删改查分页 导出 先上传后导入 NPOI批量导入 导出EXCEL的更多相关文章

  1. Node.js、express、mongodb 入门(基于easyui datagrid增删改查)

    前言 从在本机(win8.1)环境安装相关环境到做完这个demo大概不到两周时间,刚开始只是在本机安装环境并没有敲个Demo,从周末开始断断续续的想写一个,按照惯性思维就写一个增删改查吧,一方面是体验 ...

  2. 详谈easyui datagrid增删改查操作

    转自:http://blog.csdn.net/abauch_d/article/details/7734395 前几天我把easyui dadtagrid的增删改查的实现代码贴了出来,发现访问量达到 ...

  3. easyui datagrid 增删改查示例

    查询JSP页面 <!doctype html> <%@include file="/internet/common.jsp"%> <!-- 新样式右侧 ...

  4. SSM+BootStrap增删改查,以及头像上传

    先看界面 点击编辑之后 具体代码请往下看 一.jsp界面 <%@ page language="java" contentType="text/html; char ...

  5. yii2.0用gii自动补全代码做的简单增删改查,以及图片上传和展示

    首先已经用gii根据model层生成了控制器,模型,视图层. 表结构为如图所示:表名为zhoukao1,

  6. MVC与EasyUI结合增删改查

    构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(9)-MVC与EasyUI结合增删改查   在第八讲中,我们已经做到了怎么样分页.这一讲主要讲增删改查.第六讲的 ...

  7. abp(net core)+easyui+efcore实现仓储管理系统——ABP WebAPI与EasyUI结合增删改查之一(二十七)

    abp(net core)+easyui+efcore实现仓储管理系统目录 abp(net core)+easyui+efcore实现仓储管理系统——ABP总体介绍(一) abp(net core)+ ...

  8. golang学习之beego框架配合easyui实现增删改查及图片上传

    golang学习之beego框架配合easyui实现增删改查及图片上传 demo目录: upload文件夹主要放置上传的头像文件,main是主文件,所有效果如下: 主页面: 具体代码: <!DO ...

  9. Asp.Net操作MySql数据库增删改查

    Asp.Net操作MySql数据库增删改查,话不多说直接步入正题.git源码地址:https://git.oschina.net/gxiaopan/NetMySql.git  1.安装MySQL数据库 ...

随机推荐

  1. TF.Learn

    TF.Learn 手写文字识别   转载请注明作者:梦里风林Google Machine Learning Recipes 7官方中文博客 - 视频地址Github工程地址 https://githu ...

  2. expect 传参

    AAAAAAAAA(A)/app/cbsrun/sbin> cat reloadtuxconfig.exp puts "Start" set i 1 set max_i [l ...

  3. Linux 内存管理知识学习总结

    现在的服务器大部分都是运行在Linux上面的,所以,作为一个程序员有必要简单地了解一下系统是如何运行的.对于内存部分需要知道: 地址映射 内存管理的方式 缺页异常 先来看一些基本的知识,在进程看来,内 ...

  4. c++之命名空间namespace

    1命名空间解决全局变量的冲突 main.h文件 #pragma once // data命名空间的名称 namespace data { ;//外部全局变量冲突 } main.cpp #include ...

  5. Thinkphp显示系统常量信息的方法(php的用法)

    输入 :public function Main()    {        dump(get_defined_constants(true));    }显示系统信息, 其中: 'APP_PATH' ...

  6. http2.0 相对于 http1.1的优势

    1.http2.0完全是多路复用的,只需一个连接就可实现并行 可以将不同的请求夹杂在一起,只需一个连接就能加载一个页面. 2.可以让服务器将响应主动推动到客户端缓存中 当浏览器请求一个网页时,服务器除 ...

  7. hdu 2817 A sequence of numbers(快速幂)

    Problem Description Xinlv wrote some sequences on the paper a long time ago, they might be arithmeti ...

  8. 设计: ListView 接口,and the missing read-only interfaces in java collection framework

    Java的集合框架以其成功易用的设计征服了很多人(包括我),并且教科书式的诠释了泛型的应用方式. 我也是被 Joshua Bloch 的书引领入门,从中得益良多.我当然不会认为自己在设计上比他懂得更多 ...

  9. 执行eclipse,迅速failed to create the java virtual machine。

    它们必须在一排,否则会出现The Eclipse executable launcher was unable to locate its companion shared library的错误 打开 ...

  10. Citrix 服务器虚拟化之九 Xenserver虚拟机的XenMotion

    Citrix 服务器虚拟化之九 Xenserver虚拟机的XenMotion XenMotion 是 XenServer 的一项功能,能够将正在运行的虚拟机从一台 XenServer 主机上迁移到另外 ...