1、前台代码:
@{
ViewBag.Title = "xxxxxxx";
Layout = "~/xx/xxx/xxxxx.cshtml";
}
<link href="~/xxx/js/webuploader-0.1.5/webuploader.css" rel="stylesheet" />
<script type="text/javascript" src="~/xxx/js/webuploader-0.1.5/webuploader.min.js"></script>
<script type="text/javascript">
$(function () {
fileUpload();
})
function fileUpload() {
var uploader = WebUploader.create({
auto: true, // 选择文件后自动上传
// swf文件路径
swf: '~/xxx/js/webuploader-0.1.5/Uploader.swf',
// 文件接收服务端。
server: '/xxxx/xxxx/FileUpLoad',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker',
fileNumLimit: 1,
fileSingleSizeLimit: 5 * 1024 * 1024,//最大五兆
duplicate: true,
// 只允许选择xls,xlsx文件。
accept: {
title: 'Excel',
extensions: 'xls,xlsx',
mimeTypes: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
});
// 当有文件被添加进队列的时候
uploader.on('fileQueued', function (file) {
$("#thelist").append('<div id="' + file.id + '" class="item">' +
'<h4 class="info">' + file.name + '</h4>' +
'<p class="state">等待上传...</p>' +
'</div>');
uploader.on('uploadSuccess', function (file) {
$('#' + file.id).find('p.state').text('已上传');
});
uploader.on('uploadError', function (file) {
$('#' + file.id).find('p.state').text('上传出错');
});
uploader.on('uploadComplete', function (file) {
$('#' + file.id).find('.progress').fadeOut();
});
});
}
</script>
<style type="text/css">
.btn-default {
margin-left: 5px;
}
.download-file, .download-file:hover {
color: blue;
text-decoration: underline;
}
</style>
<table border="1" cellpadding="0" cellspacing="0" style="width:80%;margin:0 auto;margin-top: 4%;">
<tr>
<td align="right">下载模板:</td>
<td align="left">
<a href="~/xxxx/xxxx/xxxx模板.xlsx" title="下载" class="download-file">xxxxx模板.xlsx</a>
</td>
</tr>
<tr>
<td align="right">选择文件:</td>
<td align="left" style="height: 120px;">
<div id="uploader" class="wu-example">
@*用来存放文件信息*@
<div id="thelist" class="uploader-list"></div>
<div class="btns">
<div id="picker">选择文件并导入</div>
</div>
</div>
</td>
</tr>
</table>
2、后台文件上传代码:
public class xxxController : Controllerxxx
{
private xxxApp industryApp = new xxxApp();
private ExcelHelper excelHelper = new ExcelHelper();
/// <summary>
/// 导入xxxx数据
/// @author 王*
/// @date 2019-03-08
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public ActionResult FileUpLoad(HttpPostedFileBase file)
{
string message = "";
if (file.ContentLength > 0)
{
string fileName = file.FileName;//获取文件名称
string suffix = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf("."));//获取文件后缀名
fileName = DateTime.Now.ToString("yyyyMMddHHffss") + new Random().Next(1000, 10000).ToString() + suffix;//新的文件名称
string filePath = Server.MapPath("~/Content/FileUpload/IndustryFile/") + DateTime.Now.ToString("yyyyMMdd");//存放文件的文件夹路径
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);//创建文件夹
string savePath = Path.Combine(filePath, fileName);
file.SaveAs(savePath);//上传文件
DataTable dt = excelHelper.ExcelToDataTable(savePath, "Table1", "sheet1", ref message);//根据工具类读取上传的Excel里面的数据,返回DataTable
bool importFlag = xxxApp.ImportData(dt, ref message);//导入数据到数据库里面去
if (importFlag)
return Success(message);
else
return Error(message);
}
else
return Error("导入失败!");
}
}
3、数据导入Helper类(代码):
该方法在service层xxxApp里面
public class xxxApp
{
private xxxDbContext context = new xxxDbContext();
/// <summary>
/// 数据导入功能
/// @author 王*
/// @date 2019-03-08
/// </summary>
/// <param name="dataTable"></param>
/// <param name="message"></param>
/// <returns></returns>
public bool ImportData(DataTable dataTable, ref string message)
{
if (dataTable == null || dataTable.Rows.Count == 0)
{
message = "数据为空!导入失败。";
return false;
}
else
{
string[] columns = { "一级分类代码", "一级分类名称", "二级分类代码", "二级分类行业名称" };
List<T> parentCodeList = 获取List<T>数据源1;
List<T> ownerCodeList = 获取List<T>数据源2;
List<T> list = parentCodeList.Union(ownerCodeList).ToList();//组合两个相同的List<T>数据源;
Stopwatch sw = new Stopwatch();//定义计时器
sw.Start();
context.BulkInsert(list);//插入数据(此处使用EF6.0,EntityFramework.Extensions,提供BulkInsert方法进行数据导入。)
//注意,此时可能会出现一个错误:“System.Data.SqlClient.SqlException HResult=0x80131904 Message=从 bcp 客户端收到一个对 colid 4 无效的列长度。 Source=.Net SqlClient Data Provider StackTrace:<无法计算异常堆栈跟踪>”,导致错误出现的原因是数据表字段长度的问题。
context.SaveChanges();//将数据保存至数据库
sw.Stop();
message = string.Format("导入成功,总共导入{0}条数据,耗时:{1}毫秒。", list.Count, sw.ElapsedMilliseconds);
return true;
}
}
}
至此,干货结束。希望能帮到你哦!
男儿不展风云志,空负天生八尺躯。