页面代码:

  <form id="form1" enctype="multipart/form-data">
<div style="float:right">
&nbsp;
<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实现导入操作 方式一的更多相关文章

  1. ajax模拟表单提交,后台使用npoi实现导入操作 方式二

    页面代码: <form id="form1" enctype="multipart/form-data"> <div style=" ...

  2. 由于想要实现下载的文件可以进行选择,而不是通过<a>标签写死下载文件的参数,所以一直想要使用JFinal结合ajax实现文件下载,但是ajax实现的文件下载并不能触发浏览器的下载文件弹出框,这里通过模拟表单提交实现同样的效果。

    由于想要实现下载的文件可以进行选择,而不是通过<a>标签写死下载文件的参数,所以一直想要使用JFinal结合ajax实现文件下载(这样的话ajax可以传递不同的参数),但是ajax实现的文 ...

  3. 表单提交---前端页面模拟表单提交(form)

    有些时候我们的前端页面总没有<form></form>表单,但是具体的业务时,我们又必须用表单提交才能达到我们想要的结果,LZ最近做了一些关于导出的一些功能,需要调用浏览器默认 ...

  4. ajax form表单提交 input file中的文件

    ajax form表单提交 input file中的文件 现今的主流浏览器由于ajax提交form表单无法把文件类型数据提交到后台,供后台处理,可是开发中由于某些原因又不得不用ajax提交文件, 为了 ...

  5. <记录> axios 模拟表单提交数据

    ajax 可以通过 FormData 对象模拟表单提交数据 第一种方式:自定义FormData信息 //创建formData对象 var formData = new FormData(); //添加 ...

  6. ajax的表单提交,与传送数据

    ajax的表单提交 $.ajax ({ url: "<%=basePath%>resource/addPortDetectOne.action", dataType: ...

  7. 项目总结15:JavaScript模拟表单提交(实现window.location.href-POST提交数据效果)

    JavaScript模拟表单提交(实现window.location.href-POST提交数据效果) 前沿 1-在具体项目开发中,用window.location.href方法下载文件,因windo ...

  8. 利用HttpWebRequest模拟表单提交 JQuery 的一个轻量级 Guid 字符串拓展插件. 轻量级Config文件AppSettings节点编辑帮助类

    利用HttpWebRequest模拟表单提交   1 using System; 2 using System.Collections.Specialized; 3 using System.IO; ...

  9. HTTP通信模拟表单提交数据

    前面记录过一篇关于http通信,发送数据的文章:http://www.cnblogs.com/hyyq/p/7089040.html,今天要记录的是如何通过http模拟表单提交数据. 一.通过GET请 ...

随机推荐

  1. Docker数据卷的介绍和使用

    最近在学习docker,这篇主要讲了数据卷的作用以及使用,我用的是mac系统去操作的 1.数据卷的简介 2.数据卷的配置 (1).查看你的镜像docker images (2)运行的命令 ~$ doc ...

  2. 合并两个有序链表(剑指offer-16)

    题目描述输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则. 解答方法1:递归 /* public class ListNode { int val; List ...

  3. 微信小程序开发中遇到的几个小问题

    本地图片不显示,开发工具运行是没问题的,但真机调试却显示不了 item.img = '/goods/img/图片.png' <image src="{{item.img}}" ...

  4. CTFHub_技能树_SQL注入Ⅱ

    SQL注入 MySQL结构 进行尝试: 尝试查看表名: 尝试查看列名: 发现无法直接输出: 使用时间注入脚本跑出结果: import requests import time session = re ...

  5. node子进程(Child Process)获取硬盘分区

    node   child_process文档 child_process.exec(command[, options][, callback]) command <string> The ...

  6. 前端08 /jQuery标签操作、事件

    前端08 /jQuery标签操作.事件 目录 前端08 /jQuery标签操作.事件 1.标签内文本操作 1.1 html标签元素中的所有内容 1.2 text 标签元素的文本内容 2.文档标签操作 ...

  7. windows python的多进程

    最近打比赛,apply操作极慢,队友使用了线程池,用多核开辟多线程跑,加速. 在阿里平台上,都没问题. 我是win10系统+jupyter notebook 多线程那个模块运行,会显示一直运行,p.c ...

  8. 普通list和树状list互转

    import java.util.ArrayList; import java.util.List; public class TreeNode { private String id; privat ...

  9. GPO - Disabling Task Manager Access

    Create a GPO to disable Task Manager Access to normal users. Add an exception to Domain Admins.

  10. CocosCreator之分层管理的ListView

    前言 进入公众号回复listview即可获得demo的git地址. 之前写的一篇文章<Creator之ScrollView那些事>中提到了官方Demo中提供的ListViewCtl,只是实 ...