批量导入功能《个人框架只作为参考》
颜色相同对应调用部分
1》在XXX-config.xml中定义xlsx文件保存路径
temp
2》在Util文件夹写一个PathUtil类来接收XXX-Config.xml文件中定义保存位置,
括号内容为XXX-Config.xml加粗斜体部分
public static String getFilesRealPath() throws Exception
{
String realPath = ConfigContext.getProperty( "business.files.real.path" ) ;
return getFilesPath( realPath ) ;
}
3》在Util文件夹中定义一个UploadUtil类来调用PathUtil中的方法
public static void uploadZip( HttpServletRequest request, HttpServletResponse response ) throws Exception
{
boolean isMultipart = ServletFileUpload.isMultipartContent( request ) ;
if( isMultipart )
{
FileItemFactory factory = new DiskFileItemFactory() ;
ServletFileUpload upload = new ServletFileUpload( factory ) ;
// 得到所有的表单域,它们目前都被当作FileItem
List fileItems = upload.parseRequest( request ) ;
String id = "" ;
String oldName = "" ;
String extName = "" ;
// 如果大于1说明是分片处理
int chunks = 1 ;
int chunk = 0 ;
FileItem tempFileItem = null ;
for( FileItem fileItem : fileItems )
{
if( fileItem.getFieldName().equals( "guid" ) )
{
id = fileItem.getString() ;
}
else if( fileItem.getFieldName().equals( "name" ) )
{
oldName = new String( fileItem.getString().getBytes( "ISO-8859-1" ), "UTF-8" ) ;
extName = oldName.substring( oldName.lastIndexOf( "." ) ) ;
}
else if( fileItem.getFieldName().equals( "chunks" ) )
{
chunks = NumberUtils.toInt( fileItem.getString() ) ;
}
else if( fileItem.getFieldName().equals( "chunk" ) )
{
chunk = NumberUtils.toInt( fileItem.getString() ) ;
}
else if( fileItem.getFieldName().equals( "file" ) )
{
tempFileItem = fileItem ;
}
}
String fileName = id + extName ;
// 临时目录用来存放所有分片文件
String tempDirPath = PathUtils.getFilesTempPath() + id ;
File tempDirFile = new File( tempDirPath ) ;
if( !tempDirFile.exists() )
{
tempDirFile.mkdirs() ;
}
// 分片处理时,前台会多次调用上传接口,每次都会上传文件的一部分到后台
File tempPartFile = new File( tempDirFile, fileName + "_" + chunk + ".part" ) ;
FileUtils.copyInputStreamToFile( tempFileItem.getInputStream(), tempPartFile ) ;
tempFileItem.delete() ;
// 所有分片都存在才说明整个文件上传完成
boolean uploadDone = true ;
for( int i = 0; i < chunks; i++ )
{
File partFile = new File( tempDirFile, fileName + "_" + i + ".part" ) ;
if( !partFile.exists() )
{
uploadDone = false ;
}
}
// 所有分片文件都上传完成,将所有分片文件合并到一个文件中
if( uploadDone )
{
// 创建上传文件最终存储目录
String destDirPath = PathUtils.getFilesTempPath() ;
File destDirFile = new File( destDirPath ) ;
if( !destDirFile.exists() )
destDirFile.mkdirs() ;
File destFile = new File( destDirPath, fileName ) ;
FileOutputStream destfos = new FileOutputStream( destFile, true ) ;
for( int i = 0; i < chunks; i++ )
{
File partFile = new File( tempDirFile, fileName + "_" + i + ".part" ) ;
FileUtils.copyFile( partFile, destfos ) ;
}
destfos.close() ;
// 删除临时目录中的分片文件
FileUtils.deleteQuietly( tempDirFile ) ;
Map resultMap = new HashMap() ;
resultMap.put( "fileId", id ) ;
resultMap.put( "fileName", oldName ) ;
resultMap.put( "fileType", extName.substring( 1 ).toUpperCase() ) ;
resultMap.put( "file_real_path", destFile.getPath() ) ;
response.getWriter().print( AjaxResult.withMap( resultMap ).getOutput() ) ;
}
}
}
4》在Action写一个写一个读取XLSX文件的方法并且把读取数据保存到rowMap中
public AjaxResult batchSave(AjaxParameter param){
Map result = new HashMap<>();
try{
List
Upload方法调用UploadUtil中的uploadZip方法
@RequestMapping(params="command=upload")
public void upload(HttpServletRequest request,HttpServletResponse response) throws Exception{
UploadUtils.uploadZip(request, response);
5》页面代码
6》JS脚本页面参考代码,pageInfozhon
var uploader;
$(function () {
// 初始化操作按钮权限
_initOperations(operators);
var pageInfo = {
urls: {
uploadUrl: "页面路径.do?command=upload",
batchSaveUrl: "页面路径.do?command=batchSave",
},
parts: {
batchInsertPartId: "#batchInsertPart"
},
grid: null,
validate: {
editorForm: $("#editorForm").parsley({
errorsContainer: function (field) {
console.log(field.$element.closest("td").html())
return field.$element.closest("td").next();
}
})
}
};
pageInfo.grid = $('#datatable').DataTable($.extend($.defaultGridOpts, {
columns: columns,
order: [
[2, "DESC"]
],
ajax: function (data, callback, settings) {
$.getGridData(pageInfo.urls.listUrl, data, callback, settings)
}
}));
$(".exportFile").on('click',function () {
var paramData = {};
$.extend(paramData, $("#searchPart").getFormData());
var data = JSON.stringify(paramData);
window.location.href=pageInfo.urls.exportUrl+"¶mData="+encodeURIComponent(data);
})
$.addGridEvent(pageInfo);
$._initButtons({}, [], pageInfo);
setTimeout($.resizeContentHeight, 500);
/* var t = $(pageInfo.grid.context[0].nTable);
t.find("tbody").on('click', 'button[name=viewBTN]', function () {
var $tr = $(this).closest("tr");
$tr.closest("tbody").find("tr").removeClass("selected");
$tr.addClass("selected");
$tr.find("input[type=checkbox]").prop("checked", true);
var id = $tr.find("input[type=checkbox]").val();
$.fetchPost(pageInfo.urls.loadForViewUrl, {
id: id
}, function (result) {
$(pageInfo.parts.listPartId).hide("slow");
$(pageInfo.parts.viewPartId).show("slow", $.resizeContentHeight);
$(pageInfo.parts.viewPartId).resetFormData(result);
});
});*/
$("#batchCancelBTN").on('click', function () {
$(pageInfo.parts.batchInsertPartId).hide("slow");
$(pageInfo.parts.listPartId).show("slow", function(){
uploader.reset();
uploader.destroy();
$("#fileList").empty();
$("#fileContent").empty();
$.resizeContentHeight();
})
})
$("#resetBatchBTN").on('click',function(){
uploader.reset();
$("#fileList").empty();
})
$("#batchInsertBTN").on('click',function(){
uploader = $.init_uploader({
pick: {
id: '#filePicker',
label: '点击选择Excel文件'
},
accept: {
title: '文件',
extensions: 'xls,xlsx',
mimeTypes: [
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/zip'
].join(',')
},
fileNumLimit: 1,
threads: 1,
server: pageInfo.urls.uploadUrl
});
$("#fileContent").append("或将文件拖到这里,单次最多可选1个文件(Excel)
")
$("#saveBatchBTN").css("display", "none");
$(pageInfo.parts.listPartId).hide("slow");
$(pageInfo.parts.batchInsertPartId).show("slow", function () {
uploader.refresh();
$.resizeContentHeight();
});
})
/**
* 确认导入
*/
$("#saveBatchBTN").on('click',function(){
var submitData = {};
submitData.filesData = getFilesData();
if (submitData.filesData.length == 0) {
window.frame.info({
title: '提示',
content: '请上传一个Excel文件!'
});
return;
} else {
window.frame.showLoading();
$.fetchPost(pageInfo.urls.batchSaveUrl, submitData, function (result) {
window.frame.hideLoading();
if(result.result == "success"){
window.frame.info({
title: '提示',
content: result.message
});
$("#batchCancelBTN").trigger("click");
}else{
window.frame.info({
title: '提示',
content: result.message
});
}
});
}
})
$("#batchCancelBTN").on('click',function(){
$("#batchCancelBTN").trigger("click");
})
/**
* 上传完成后的回调函数。
* @param data 上传完成后的返回数据
*/
window.singleFileUploadAfter = function(data) {
var product = {
wuid: data.wuid,
fileId: "",
title: data.fileName,
imgUrl: "../custom/images/" + data.fileType + ".png",
realPath: data.file_real_path,
type: data.fileType
};
$("#saveBatchBTN").css("display", "inline-block");
addFileBlock(product, true);
}
/**
* 添加上传文件显示的块。
* @param data 上传文件显示块的数据
* @param allowEdit 是否允许编辑
*/
function addFileBlock(data, allowEdit) {
var $fileListdiv = $("#fileList");
var items = $fileListdiv.find(".productItemBlock");
var itemsLen = items.length;
var $block;
if (itemsLen % 4 == 0) {
var html = [
'',
' ',
' ',
' ',
addUploadFileBlock(data),
' ',
' ',
''
].join('');
$block = $(html).appendTo($fileListdiv);
} else {
var html = [
'',
' ',
' ',
addUploadFileBlock(data),
' ',
''
].join('');
$block = $(html).appendTo($fileListdiv.find("div.row:last"));
}
if (allowEdit) {
$block.find(".productItemBlock").on('mouseenter', function () {
$(this).find(".topHead").stop().animate({
height: 30
});
});
$block.find(".productItemBlock").on('mouseleave', function () {
$(this).find(".topHead").stop().animate({
height: 0
});
});
$block.find(".fa-trash-o").on('click', function () {
removeFile(this);
});
}
$.resizeContentHeight();
}
/**
* 获取上传文件数据。
* @returns {Array} 上传文件数据
*/
function getFilesData() {
var filesData = [];
$(pageInfo.parts.batchInsertPartId).find("#fileList .productItemBlock").each(function (index, item) {
var id = $(item).find("input[type=hidden][name=fileId]").val();
var fileName = $(item).find(".productItem--description").text();
var name = $(item).find(".productItem--title span").text();
var fileType = $(item).find(".productItem--number").text();
var filePath = $(item).find("input[type=hidden][name=realPath]").val();
filesData.push({
id: id,
name: "",
fileName: fileName,
fileType: fileType,
filePath: filePath
});
});
return filesData;
}
/**
* 删除文件
* @param el 删除按钮对象
*/
function removeFile(el) {
var wuid = $(el).data("wuid");
var $block = $(el).closest(".col-sm-3");
var fileId = $block.find("input[type=hidden][name=fileId]").val();
if (fileId == "") {
$block.remove();
if (uploader.getFile(wuid))
uploader.removeFile(wuid);
}
$.resizeContentHeight();
}
});
7 》定义实体类Entity
@Entity
@Table(name = "business_cost_center")
public class BusinessCostCenterEntity extends AbstractEntityBusiness {
private int delFlag; //删除标记
private String costCode; //成本中心代码
private String costRange; //范围
private String costCompany; //公司
private String costInstruction; //简要说明
//获取 删除标记
@Column(name = "del_flag")
public int getDelFlag() {
return delFlag;
}
//设置 删除标记
public void setDelFlag(int delFlag) {
this.delFlag = delFlag;
}
//获取 成本中心代码
@Column(name = "cost_code",length=100)
@ExcelField(title="成本中心代码", align=2, sort=5)
public String getCostCode() {
return costCode;
}
//设置 成本中心代码
public void setCostCode(String costCode) {
this.costCode = costCode;
}
//获取 范围
@Column(name = "cost_range",length=100)
@ExcelField(title="范围", align=2, sort=10)
public String getCostRange() {
return costRange;
}
//设置 范围
public void setCostRange(String costRange) {
this.costRange = costRange;
}
//获取 公司
@Column(name = "cost_company",length=100)
@ExcelField(title="公司", align=2, sort=15)
public String getCostCompany() {
return costCompany;
}
//设置 公司
public void setCostCompany(String costCompany) {
this.costCompany = costCompany;
}
//获取 简要说明
@Column(name = "cost_instruction",length=100)
@ExcelField(title="简要说明 ", align=2, sort=20)
public String getCostInstruction() {
return costInstruction;
}
//设置 简要说明
public void setCostInstruction(String costInstruction) {
this.costInstruction = costInstruction;
}
@Override
public String obtainInformation() {
// TODO Auto-generated method stub
return null;
}
}