jexcel_将excel数据导入到页面+导入到数据(SQL)

1. excel导入到页面_模板.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="excel导入到页面_模板.aspx.cs" Inherits="excel导入到页面_模板" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>SSC</title>

<%--CSS--%>
<link href="/css/jexcel.css" rel="stylesheet" />
<link href="/css/bootstrap.min.css" rel="stylesheet" />

<%--JS--%>
<%--jquery和bootstrap--%>
<script src="../js/jquery.min.js"></script>
<script src="../js/jquery-1.10.2.min.js"></script>
<script src="../js/bootstrap.min.js"></script>

<%--excel导入--%>
<script src="../js/xlsx.core.min.js"></script>


<%--Jexcel包--%>
<script src="../js/jexcel.js"></script>
<script src="../js/jsuites.js"></script>


<style>

#excelFileInput {
display: none; /* 隐藏原始的文件输入框 */
}

#customFileInput {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>

<!-- 将按钮和文件输入框合并在一起 -->
<div>
<label for="excelFileInput" id="customFileInput">选择 Excel 文件</label>
<input type="file" id="excelFileInput" accept=".xls, .xlsx" />
<button id="deletedRow" type="button" class="btn btn-danger" onclick="myDeleteRow()">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>删除行 OK
</button>
<%--显示选中的ID号(唯一值)--%>
<input type="text" id="my_textbox" />
</div>

<%--表格--%>
<div id="spreadsheet" class="container"></div>

<!-- 将按钮和文件输入框合并在一起 -->
<script>
document.getElementById('excelFileInput').addEventListener('change', function () {
var fileInput = document.getElementById('excelFileInput');
var file = fileInput.files[0];

if (file) {
// 执行处理 Excel 文件的逻辑,可以使用第三方库如 SheetJS 等
// 这里只是一个示例,实际情况中可能需要更复杂的处理
alert('已选择文件: ' + file.name);
} else {
alert('请先选择文件');
}
});
</script>
</body>

 

<script type="text/javascript">
<!--得出一个永远不会重复的日期格式的字符串,包括毫秒,用于AJAX输出一个不重复参数,以避免不刷新,function全部写在head节点内-->
function getNowTime() {
var date = new Date();
this.year = date.getFullYear();
this.month = date.getMonth() + 1;
this.date = date.getDate();
this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
this.milliSeconds = date.getMilliseconds();
var currentTime = this.year + '-' + this.month + '-' + this.date + ' ' + this.hour + ':' + this.minute + ':' + this.second + '.' + this.milliSeconds;
return currentTime;
}
</script>


<%--将excel内容先存入数据库,再将数据显示到页面--%>
<script type="text/javascript">

//首先监听input框的变动,选中一个新的文件会触发change事件
document.querySelector("#excelFileInput").addEventListener("change", function () {

//获取到选中的文件
var file = document.querySelector("#excelFileInput").files[0];

//判断文件类型
var type = file.name.split('.');
if (type[type.length - 1] !== 'xlsx' && type[type.length - 1] !== 'xls' && type[type.length - 1] !== 'XLS' && type[type.length - 1] !== 'XLSX') {
alert('只能选择excel文件导入');
return false;
}

//新建一个对象_读取文件
const reader = new FileReader();

//读取二进制字符串
reader.readAsBinaryString(file);

//文件读取完时触发一个方法
reader.onload = function (e) {
const data1 = e.target.result; //把读出来的二进制字符串赋值给data1变量
const zzexcel = window.XLSX.read(data1, { //从XLS文件中读取
type: 'binary', //数据类型_二进制数据
cellDates: true, //将 12/13/22 变为 2022/12/13 追加无效 。。。重要、重要
dateNF: 'yyyy/mm/dd' //指定日期格式为四位数的年份 。。。重要、重要
});

//申明变量result
const result = [];

//从EXCEL中取值,放入变量result
for (let i = 0; i < zzexcel.SheetNames.length; i++) {
const newData = window.XLSX.utils.sheet_to_json(zzexcel.Sheets[zzexcel.SheetNames[i]]); //xlsx.core.min.js插件 将excel数据取出

//console.log(newData); //F12 控制台中_确认
result.push(...newData)
}

var data2 = JSON.stringify(result) //用变量接收JSON数据,JSON.stringify(result)将对象变为字符串
var excel_data = JSON.parse(data2); //JSON.parse()将字符串变为对象 。。。重要、重要
//console.log(excel_data); //F12 控制台中_确认

jspreadsheet(document.getElementById('spreadsheet'), {
//往jexcel中装入数据
data: excel_data,
});

////逐条提取数据
for (var i = 0; i < result.length; i++) {
//console.log(JSON.stringify(result[i])); //EXCEL中每一行数据 F12的控制台中_确认
var strJsonData = JSON.stringify(result[i]);
//alert(strJsonData); //弹窗_确认
//}


//将excel_data传给后台,写入数据库
$.ajax({
//新项目修改点*********************************
url: "/excel导入到页面_模板.ashx",
datatype: "json",
data: { "RequestType": "inserted_excel_data", "excel_data": strJsonData },
success: function (data) {
//alert("excel导入成功")
document.getElementById('spreadsheet').jexcel.refresh(); //刷新表格
},
error: function (error) {
alert("excel导入不成功,格式、字段名与网页中的表格不一致");

}
});

}

//刷新表格 ????没成功???
jspreadsheet(document.getElementById('spreadsheet')).updateTable();
}
});

</script>


<script type="text/javascript">

var mySpreadsheet = jspreadsheet(document.getElementById('spreadsheet'), {

//新项目修改点*********************************
url: '/Handler1.ashx', // 获取数据
search: true, // 搜索 搜索自定义的新事件 onsearchstart、onserchrow *
filters: true, // 列搜索,是否需要过滤器 过滤数据
async: true,
allowExport: true, // 是否允许导出
colWidths: [50, 80, 100, 100, 100, 80, 100, 100, 80, 80, 100, 70, 70, 70, 70, 80, 100], //列宽
tableOverflow: true, // 是否允许表溢出溢出的时候右边有那个滚动条
tableWidth: "1520px", // 表宽度
tableHeight: "430px", // 表高度
pagination: 10, // 每页显示10行数据 *
paginationOptions: [10, 15, 20, 50], //用户自主选择每页需展示的数据条数 *
tabs: true, //标签
toolbar: true, //工具栏 需加载<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons" /> 目前使用不可
//toolbar: '#toolbar', //工具栏
editable: true, // 启用行内编辑
striped: true, //表格斑马纹
sortable: true, //排序
sortOrder: "asc", //排序方式

 

//日期选取器 OK
options: {
format: 'DD/MM/YYYY', //日期格式
readonly: 0, //允许键盘输入日期
today: 0, //今天是默认值
time: 0, //显示时间选择器
resetButton: true, //显示重置按钮
placeholder: '', //占位符
// 翻译
months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
weekdays_short: ['Su', 'M', 'T', 'W', 'T', 'F', 'Sa'],
value: null, //值
onclose: null, //onclose事件
onchange: null, //onchange事件
fullscreen: false, //全屏显示(这是屏幕尺寸<800时自动设置的)
},

//列属性 OK
columns: [
//新项目修改点*********************************
{ field: 'id', title: 'DBid', sortable: true, align: 'center', },
//{ field: 'checkbox', title: 'checkbox', sortable: true, align: 'center', type: 'checkbox' },
//{ field: 'checkbox', title: 'checkbox', sortable: true, align: 'center', type: 'checkbox',format: 'YYYY/MM/DD', },
{ field: 'type', title: 'type', sortable: true, align: 'center', },
{ field: 'Shipto', title: 'Shipto', sortable: true, align: 'center', },
{ field: 'Soldto', title: 'Soldto', sortable: true, align: 'center', },
{ field: 'MOsPONo', title: 'MOsPONo', sortable: true, align: 'center', },

],


//事件 必须先完成事件的function
//onchange: changed, //修改单元格并同步数据库 之前onchange输成了onchanged,不能出现alert()弹窗*
//onselection: selectionActive,//点击事件
//allowDeleteColumn: false,//不允许删除列
//allowDeleteRow: true,//允许删除行
//allowDeletingAllRows: true,//允许删除所有行
//allowRenameColumn: false,//不允许重命名列
//allowInsertRow: false,//不允许插入行
//allowInsertColumn: false,//不允许插入列

});

</script>
</html>

2. excel导入到页面.ashx (后端逻辑)

<%@ WebHandler Language="C#" Class="excel导入到页面_模板" %>

using System;
using System.Web;
using System.Data;
using System.IO;
using System.Data.SqlClient; //数据库
using Newtonsoft.Json; //操作json库
using System.Text;

public class excel导入到页面_模板 : IHttpHandler
{
CommonClass class1 = new CommonClass();

//创建一个简单的Person类
public class Person
{
//新项目修改点*********************************
public string No;
public string id;
public string type;
public string Shipto;
public string Soldto;
public string MOsPONo;
}

string excel_data;

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";

//前端获取excel表数据_写入数据库
if (context.Request["RequestType"] == "inserted_excel_data")
{
//接受页面传来的值
string excel_data = context.Request["excel_data"].ToString();

//字符处理,去掉斜杠“/”
StringBuilder s0 = new StringBuilder(excel_data); //去掉JSON格式内的反斜杠
var json = JsonConvert.DeserializeObject<Person>(s0.ToString()); //反序列

//新项目修改点*********************************
string s2 = "select count(ID) from outstanding2 WHERE ID=" + json.id; //统计数据条数
string ss = class1.ExecScalar(class1.GetConnection2(), s2);
System.Diagnostics.Debug.WriteLine("ss : " + ss); //确认 (调试-窗口-输出)

//操作数据库
SqlConnection conn = new SqlConnection("sserver=****;database=****;uid=****;pwd=*******");
conn.Open();
SqlCommand cmd1 = new SqlCommand(s2, conn); //用来执行查询语句
cmd1.ExecuteNonQuery(); //执行SQL语句,返回受影响的行数
cmd1.Dispose(); //释放资源
conn.Close();

//如果ID存在,那么ss大于1,更新数据;如果ID不存在,那么ss=0,插入新数据
if (ss == "0")
{
//新项目修改点*********************************
string s1 = "insert into outstanding2 (type,Shipto,Soldto,MOsPONo) values ('"
+ json.type + "','"
+ json.Shipto + "','"
+ json.Soldto + "','"
+ json.MOsPONo + "')";


System.Diagnostics.Debug.WriteLine("s1 : " + s1); //确认 (调试-窗口-输出) 20240227使用OK

//往数据库写入
//SqlConnection conn = new SqlConnection("server=****;database=****;uid=****;pwd=*******");
conn.Open();
SqlCommand cmd2 = new SqlCommand(s1, conn); //用来执行查询语句
cmd2.ExecuteNonQuery(); //执行SQL语句,返回受影响的行数
cmd2.Dispose(); //释放资源
conn.Close();

}
else
{
//新项目修改点*********************************
string s3 = "update outstanding2 set " +
"type ='" + json.type + "'," +
"Shipto ='" + json.Shipto + "'," +
"Soldto ='" + json.Soldto + "'," +
"MOsPONo ='" + json.MOsPONo + "'";


//System.Diagnostics.Debug.WriteLine("s3 : " + s3); //确认 (调试-窗口-输出)

//往数据库写入
//SqlConnection conn = new SqlConnection("server=****;database=****;uid=****;pwd=*******");
conn.Open();
SqlCommand cmd3 = new SqlCommand(s3, conn); //用来执行查询语句
cmd3.ExecuteNonQuery(); //执行SQL语句,返回受影响的行数
cmd3.Dispose(); //释放资源
conn.Close();
};

};

}

public bool IsReusable
{
get
{
return false;
}
}

}

 

3.excel 数据

ID    是否售后依赖    Shipto    Soldto    MOsPONo
1    是        1    3
2    否        2    4

 

posted @ 2023-12-07 16:02  AutomationAnywhere  阅读(180)  评论(0)    收藏  举报