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请 ...
随机推荐
- Netty 源码解析(五): Netty 的线程池分析
今天是猿灯塔“365篇原创计划”第五篇. 接下来的时间灯塔君持续更新Netty系列一共九篇 Netty 源码解析(一): 开始 Netty 源码解析(二): Netty 的 Channel Netty ...
- [POJ3613] Cow Relays(Floyd+矩阵快速幂)
解题报告 感觉这道题gyz大佬以前好像讲过一道差不多的?然鹅我这个蒟蒻发现矩阵快速幂已经全被我还给老师了...又恶补了一遍,真是恶臭啊. 题意 给定一个T(2 <= T <= 100)条边 ...
- C#几种单例模式
/** * 单例模式-饿汉式 */ public class Singleton { // 在定义的时候就初始化_instance, private static Singleton _instanc ...
- CSS(三) - 定位模型 - float的几要素
要点 1.浮动盒子会脱离文文档流,不会在占用空间. 2.非浮动元素几乎当浮动盒子根本不存在一样该怎么布局怎么布局不会被影响 3.非浮动元素中的文本内容会记住浮动元素的大小,并在排布时避开它,为其留出响 ...
- 谈谈你对this的理解
this的指向不是在编写时确定的,而是在执行时确定的,同时,this不同的指向在于遵循了一定的规则. 1.默认情况下,指向全局,浏览器的话就是指向window 2.如果函数被调用的位置存在上下文,那么 ...
- flask 源码专题(九):flask扩展点
1. 信号(源码) 信号,是在flask框架中为我们预留的钩子,让我们可以进行一些自定义操作. pip3 install blinker 2. 根据flask项目的请求流程来进行设置扩展点 中间件 # ...
- redis(六):Redis 字符串(String)
Redis 字符串数据类型的相关命令用于管理 redis 字符串值,基本语法如下: 语法 redis 127.0.0.1:6379> COMMAND KEY_NAME 实例 redis 127. ...
- Python之爬虫(二十四) 爬虫与反爬虫大战
爬虫与发爬虫的厮杀,一方为了拿到数据,一方为了防止爬虫拿到数据,谁是最后的赢家? 重新理解爬虫中的一些概念 爬虫:自动获取网站数据的程序反爬虫:使用技术手段防止爬虫程序爬取数据误伤:反爬虫技术将普通用 ...
- unity-TextAsset
定义: 当把Text files导到unity,将会变成TextAsset. 支持的格式: .txt .html .htm .xml .bytes .json .csv .yaml .fnt 注意 不 ...
- 【其他-小技巧-Uipath】VB语法操作DataTable分组并求和
需要对DataTable分组求和的语法:VB.net 和C#中还有点不太一样.最后试了好多方法,要这么写 我的dataTabel数据: (From p In dataTabel.AsEnumerabl ...