ajax模拟表单提交,后台使用npoi实现导入操作 方式一
页面代码:
- <form id="form1" enctype="multipart/form-data">
- <div style="float:right">
-
- <button type="button" class="btn btn-primary" onclick="$('#fileUpload').click()" id="reviewFile">浏览</button>
- <button class="btn btn-primary" type="button" style="margin-left:5px;height:30px;" id="dataExport">批量导入</button>
- <input type="button" class="btn btn-primary" style="margin-left:5px;height:30px;" id="downLoad" value="下载模板">
- </div>
- <div style="float:right;margin-top:5px">
- <input id="fileUpload" name="fileUpload" type="file" style="display:none" />
- <input id="fileText" type="text" class="form-control" disabled />
- </div>
- <script>
- $("#fileUpload").change(function () {
- $("#fileText").val($(this).val());
- })
- </script>
- </form>
js代码:
- //导入excel数据
- $("#dataExport").click(function () {
- var formData = new FormData($('form')[0]);
- $.ajax({
- url: '/BaseInfoPage/Upload',
- type: 'POST',
- xhr: function () {
- return $.ajaxSettings.xhr();
- },
- data: formData,
- cache: false,
- contentType: false,
- processData: false,
- success: function (data) {
- if (data == "导入成功!") {
- layer.msg(data, { icon: 1, time: 5000 }, function () {
- location.reload(); //刷新父页面 第二个参数设置msg显示的时间长短
- });
- } else {
- layer.msg(data, { icon: 0, time: 5000 }, function () {
- return;
- });
- }
- },
- error: function (e) {
- layer.msg(e, { icon: 0, time: 5000 }, function () {
- return;
- });
- }
- });
- })
c#后台代码:
- public string Upload(HttpPostedFileBase fileUpload)
- {
- if (fileUpload == null)
- {
- return "文件为空";
- }
- string fileExtension = Path.GetExtension(fileUpload.FileName);//获取文件名后缀
- try
- {
- //判断文件类型
- if (".xls" == fileExtension || ".xlsx" == fileExtension)
- {
- //将硬盘路径转化为服务器路径的文件流
- //string fileName = Path.Combine(Request.MapPath("~/ExcelTemplate"), Path.GetFileName(fileUpload.FileName));
- string fileName = fileUpload.FileName;
- string filePath = "";
- filePath = CSysCfg.exFilePath;
- if (!Directory.Exists(filePath))
- {
- Directory.CreateDirectory(filePath);
- }
- //保存模板到服务器
- fileUpload.SaveAs(filePath + "\\" + fileName);
- //从NPOI读取到的Excel的数据,保存到excelTable里
- DataTable excelTable = new DataTable();
- excelTable = GetExcelDataTable(filePath + "\\" + fileName);//自定义方法
- //把表的中文表头转换成数据库表中对应的英文
- DataTable dbdata = new DataTable();
- dbdata.Columns.Add("ltl_Id");
- dbdata.Columns.Add("ltl_PlateId");
- dbdata.Columns.Add("ltl_StarteTime");
- dbdata.Columns.Add("ltl_EndTime");
- for (int i = ; i < excelTable.Rows.Count; i++)
- {
- DataRow dr = excelTable.Rows[i];
- DataRow dr_ = dbdata.NewRow();
- dr_["ltl_Id"] = dr["申请编号"];
- dr_["ltl_PlateId"] = dr["车牌号码"];
- dr_["ltl_StarteTime"] = dr["开始日期"];
- dr_["ltl_EndTime"] = dr["结束日期"];
- dbdata.Rows.Add(dr_);
- }
- RemoveEmpty(dbdata);//自定义方法
- //获取连接字符串,调用批量插入数据库的方法 需更改web.config添加配置
- string constr = System.Configuration.ConfigurationManager.AppSettings["exportData"];
- SqlBulkCopyByDatatable(constr, "LargeTransportLicense", dbdata);//自定义方法(连接字符串,表名,数据)
- return "导入成功!";
- }
- else
- {
- return "只可以选择Excel文件!";
- }
- }
- catch
- {
- return "导入失败!";
- }
- }
- // 从Excel中获取数据到DataTable
- public static DataTable GetExcelDataTable(string filePath)
- {
- IWorkbook Workbook;
- DataTable table = new DataTable();
- try
- {
- using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
- {
- //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
- string fileExt = Path.GetExtension(filePath).ToLower();
- if (fileExt == ".xls")
- {
- Workbook = new HSSFWorkbook(fileStream);
- }
- else if (fileExt == ".xlsx")
- {
- Workbook = new XSSFWorkbook(fileStream);
- }
- else
- {
- Workbook = null;
- }
- }
- //定位在第一个sheet
- ISheet sheet = Workbook.GetSheetAt();
- //第一行为标题行
- IRow headerRow = sheet.GetRow();
- int cellCount = headerRow.LastCellNum;// 是当前行的总列数
- int rowCount = sheet.LastRowNum;////LastRowNum 是当前表的总行数-1(注意)
- //循环添加标题列
- for (int i = headerRow.FirstCellNum; i < cellCount; i++)
- {
- DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
- table.Columns.Add(column);
- }
- List<string> regionName = new List<string>();
- //数据
- 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] = GetCellValue2(row.GetCell(j));
- }
- }
- }
- table.Rows.Add(dataRow);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- return table;
- }
- //数据类型判断 方式一
- private static string GetCellValue(NPOI.SS.UserModel.ICell cell)
- {
- if (cell == null)
- {
- return string.Empty;
- }
- else
- {
- 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();
- }
- }
- }
- }
- //数据类型判断,并设置为对应的数据类型 方式二
- public static object GetCellValue2(NPOI.SS.UserModel.ICell cell)
- {
- object value = null;
- if (cell == null)
- {
- value = ;
- }
- try
- {
- if (cell.CellType != CellType.Blank)
- {
- switch (cell.CellType)
- {
- case CellType.Blank:
- value = string.Empty;
- break;
- case CellType.Numeric:
- // 日期
- if (DateUtil.IsCellDateFormatted(cell))
- {
- value = cell.DateCellValue;
- }
- else
- {
- // 数值
- value = cell.NumericCellValue;
- }
- break;
- case CellType.Boolean:
- // Boolean type
- value = cell.BooleanCellValue;
- break;
- case CellType.Formula:
- value = cell.CellFormula;
- break;
- default:
- // String type
- value = cell.StringCellValue;
- break;
- }
- }
- else
- {
- value = ;
- }
- }
- catch (Exception)
- {
- value = ;
- }
- return value;
- }
- /// <summary>
- /// 大数据插入
- /// </summary>
- /// <param name="connectionString">目标库连接</param>
- /// <param name="TableName">目标表</param>
- /// <param name="dtSelect">来源数据</param>
- public static void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dtSelect)
- {
- using (SqlConnection conn = new SqlConnection(connectionString))
- {
- using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))
- {
- try
- {
- sqlbulkcopy.DestinationTableName = TableName;
- sqlbulkcopy.BatchSize = ;
- sqlbulkcopy.BulkCopyTimeout = ;//不限时间
- for (int i = ; i < dtSelect.Columns.Count; i++)
- {
- sqlbulkcopy.ColumnMappings.Add(dtSelect.Columns[i].ColumnName, dtSelect.Columns[i].ColumnName);
- }
- sqlbulkcopy.WriteToServer(dtSelect);
- }
- catch (System.Exception ex)
- {
- throw ex;
- }
- }
- }
- }
- //在导入Excel数据的时候,有时候会有空行,用RemoveEmpty方法去空
- protected void RemoveEmpty(DataTable dt)
- {
- List<DataRow> removelist = new List<DataRow>();
- for (int i = ; i < dt.Rows.Count; i++)
- {
- bool IsNull = true;
- for (int j = ; j < dt.Columns.Count; j++)
- {
- if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
- {
- IsNull = false;
- }
- }
- if (IsNull)
- {
- removelist.Add(dt.Rows[i]);
- }
- }
- for (int i = ; i < removelist.Count; i++)
- {
- dt.Rows.Remove(removelist[i]);
- }
- }
注:此方法需在web.config中添加配置
- <appSettings>
- <add key="exportData" value="server=xxx;database=xx;uid=xxx;pwd=xxx" />
- </appSettings>
ajax模拟表单提交,后台使用npoi实现导入操作 方式一的更多相关文章
- ajax模拟表单提交,后台使用npoi实现导入操作 方式二
页面代码: <form id="form1" enctype="multipart/form-data"> <div style=" ...
- 由于想要实现下载的文件可以进行选择,而不是通过<a>标签写死下载文件的参数,所以一直想要使用JFinal结合ajax实现文件下载,但是ajax实现的文件下载并不能触发浏览器的下载文件弹出框,这里通过模拟表单提交实现同样的效果。
由于想要实现下载的文件可以进行选择,而不是通过<a>标签写死下载文件的参数,所以一直想要使用JFinal结合ajax实现文件下载(这样的话ajax可以传递不同的参数),但是ajax实现的文 ...
- 表单提交---前端页面模拟表单提交(form)
有些时候我们的前端页面总没有<form></form>表单,但是具体的业务时,我们又必须用表单提交才能达到我们想要的结果,LZ最近做了一些关于导出的一些功能,需要调用浏览器默认 ...
- ajax form表单提交 input file中的文件
ajax form表单提交 input file中的文件 现今的主流浏览器由于ajax提交form表单无法把文件类型数据提交到后台,供后台处理,可是开发中由于某些原因又不得不用ajax提交文件, 为了 ...
- <记录> axios 模拟表单提交数据
ajax 可以通过 FormData 对象模拟表单提交数据 第一种方式:自定义FormData信息 //创建formData对象 var formData = new FormData(); //添加 ...
- ajax的表单提交,与传送数据
ajax的表单提交 $.ajax ({ url: "<%=basePath%>resource/addPortDetectOne.action", dataType: ...
- 项目总结15:JavaScript模拟表单提交(实现window.location.href-POST提交数据效果)
JavaScript模拟表单提交(实现window.location.href-POST提交数据效果) 前沿 1-在具体项目开发中,用window.location.href方法下载文件,因windo ...
- 利用HttpWebRequest模拟表单提交 JQuery 的一个轻量级 Guid 字符串拓展插件. 轻量级Config文件AppSettings节点编辑帮助类
利用HttpWebRequest模拟表单提交 1 using System; 2 using System.Collections.Specialized; 3 using System.IO; ...
- HTTP通信模拟表单提交数据
前面记录过一篇关于http通信,发送数据的文章:http://www.cnblogs.com/hyyq/p/7089040.html,今天要记录的是如何通过http模拟表单提交数据. 一.通过GET请 ...
随机推荐
- centos彻底删除文件夹创建文件
centos彻底删除文件夹.文件命令(centos 新建.删除.移动.复制等命令: 1.新建文件夹 mkdir 文件名 新建一个名为test的文件夹在home下 view source1 mkdir ...
- python入门007
一.深浅copy 浅拷贝:是把原列表第一层的内存地址完全拷贝一份给新列表.即只能保证对原列表中第一层地址(不可变类型)的改操作不受影响,涉及到原列表中第二层地址(可变类型)的改操作时,原列表变,新列表 ...
- AbstractQueuedSynchronizer(AQS)抽丝剥茧深入了解JUC框架原理
目录 简介 Lock简单实用 主体框架 原理解析 独占锁 AQS数据结构 CLH数据结构 acquire实现步骤 addWaiter acquireQueued shouldParkAfterFail ...
- Let's GO(三)
人生苦短,Let's GO Let's GO(一) Let's GO(二) Let's GO(三) Let's GO(四) 今天我学了什么? 1. 结构体(struct) /* type TYPENA ...
- DVWA学习记录 PartⅢ
CSRF 1. 题目 CSRF,全称Cross-site request forgery,翻译过来就是跨站请求伪造,是指利用受害者尚未失效的身份认证信息(cookie.会话等),诱骗其点击恶意链接或者 ...
- flask 源码专题(十一):LocalStack和Local对象实现栈的管理
目录 04 LocalStack和Local对象实现栈的管理 1.源码入口 1. flask源码关于local的实现 2. flask源码关于localstack的实现 3. 总结 04 LocalS ...
- Python并发编程05 /死锁现象、递归锁、信号量、GIL锁、计算密集型/IO密集型效率验证、进程池/线程池
Python并发编程05 /死锁现象.递归锁.信号量.GIL锁.计算密集型/IO密集型效率验证.进程池/线程池 目录 Python并发编程05 /死锁现象.递归锁.信号量.GIL锁.计算密集型/IO密 ...
- C#根据反射动态创建ShowDoc接口文本信息
我目前每天主要工作以开发api为主,这都离不开接口文档.如果远程对接的话前端总说Swagger不清晰,只能重新找一下新的接口文档.ShowDoc就是一个不错的选择,简洁.大方.灵活部署. 但是话说回来 ...
- 第四章:View的工作原理
4.1 ViewRoot和DecorView ViewRoot对应于ViewRootImplement类,它是连接WindowManager和DecorView的纽带,View的三大流程均是通过Vie ...
- Python Ethical Hacking - VULNERABILITY SCANNER(4)
Extracting & Submitting Forms Automatically Target website:http://10.0.0.45/dvwa/vulnerabilities ...