导出文件js:
function exportStatement(){
var dt = $("#XXFrom").serializeJSON();
$.ajax({
type : "POST",
contentType : 'application/json',
url : context+'/XXX/XXX.json',
data : JSON.stringify(dt),
dataType : "json",
beforeSend: function () {
// 禁用按钮防止重复点击
$("#XXXBtn").attr({ disabled: "disabled" });
},
success : function(data) {
if (data != null && data.state == 200) {
if(data.data.length>0){
for(var i=0;i<data.data.length;i++){
//数据处理
data.data[i].XX=amounttoReal(data.data[i].XX);
data.data[i].XX=timeStamp2String(data.data[i].XX);
data.data[i].XX=timeStamp2String(data.data[i].XX);
data.data[i].XX=timeStamp2String(data.data[i].XX);
data.data[i].XX=timeStamp2String(data.data[i].XX);
data.data[i].XX= XXMap[data.data[i].XX];
data.data[i].XX= XXMap[data.data[i].XX];
data.data[i].XX= XXMap[data.data[i].XX];
data.data[i].XX= XXMap[data.data[i].XX];
}
//设置表头
var codesList = new Array();
codesList.push("X");
codesList.push("X");
codesList.push("X");
codesList.push("x");
codesList.push("x");
codesList.push("x");
codesList.push("x");
codesList.push("x");
codesList.push("x");
codesList.push("x");
codesList.push("x");
codesList.push("x");
codesList.push("x");
codesList.push("x");
codesList.push("x");
var dd = new Date().toLocaleDateString();
//导出excel
sendJSONToExcelConvertor(data.data,dd+"XXX",codesList);
}else{
swal("没有数据导出")
};
}else{
swal("查询出错");
};
},
complete: function () {
$("#XXBtn").removeAttr("disabled");
},
});
}
/**
* JSONData:josn数据
* FileName:文件名
* ShowLabel:表头
*/
function sendJSONToExcelConvertor(JSONData, FileName, ShowLabel) {
//先转化json
var arrData = typeof(JSONData) != 'object' ? JSON.parse(JSONData) : JSONData;
var excel = new StringBuffer();
excel.append('<table style="vnd.ms-excel.numberformat:@">');
//设置表头
var row = new StringBuffer();
row.append('<tr>');
for (var i = 0, l = ShowLabel.length; i < l; i++) {
row.append('<td>' + ShowLabel[i] + '</td>');
}
//换行
excel.append(row);
excel.append('</tr>');
//换行
for (var i = 0; i < arrData.length; i++) {
var td = new StringBuffer();
td.append('<tr><td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td>'+
'<td>' + isNull(arrData[i].xx,1) + '</td></tr>');
excel.append(td);
}
excel.append('</table>');
var excelFile = new StringBuffer();
excelFile.append("<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>");
excelFile.append('<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">');
excelFile.append('<meta http-equiv="content-type" content="application/vnd.ms-excel');
excelFile.append('; charset=UTF-8">');
excelFile.append("<head>");
excelFile.append("<!--[if gte mso 9]>");
excelFile.append("<xml>");
excelFile.append("<x:ExcelWorkbook>");
excelFile.append("<x:ExcelWorksheets>");
excelFile.append("<x:ExcelWorksheet>");
excelFile.append("<x:Name>");
excelFile.append("{worksheet}");
excelFile.append("</x:Name>");
excelFile.append("<x:WorksheetOptions>");
excelFile.append("<x:DisplayGridlines/>");
excelFile.append("</x:WorksheetOptions>");
excelFile.append("</x:ExcelWorksheet>");
excelFile.append("</x:ExcelWorksheets>");
excelFile.append("</x:ExcelWorkbook>");
excelFile.append("</xml>");
excelFile.append("<![endif]-->");
excelFile.append("</head>");
excelFile.append("<body>");
excelFile.append(excel);
excelFile.append("</body>");
excelFile.append("</html>");
var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = FileName + ".xls";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
function StringBuffer() {
this.content = new Array;
}
StringBuffer.prototype.append = function(str) {
this.content.push(str);
}
StringBuffer.prototype.prepend = function(str) {
this.content.unshift(str);
}
StringBuffer.prototype.toString = function() {
return this.content.join("");
}
/*excel导出-----------------------end--------------------------------*/
后台版
js:
function exportStatement(){
location.href=encodeURI(context+'/XXX/XXX.json?parameterMap='+ JSON.stringify(dt));
}
serviceImpl:
public void reviewDecisionExport(HttpServletRequest request, HttpServletResponse response) {
XXX record = new XXX();
try {
// 对应前端的编码,在这里进行解码,并解析json为Map
String value = URLDecoder.decode(request.getParameter("parameterMap"), "UTF-8");
record = JSON.parseObject(value,BusinessReviewOrder.class);
System.out.println("sshsuhsu"+record.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//获取数据
List<XXXDto> list = XXXMapper.selecXXXList(record);
if (!list.isEmpty()) {
// 3 生成excel
String []title = {"订单号","推测分","初审人","初审人决策主原因","子原因","初审备注","终审人","终审人决策主原因","子原因","终审备注","分期金额","初审决策时间","终审决策时间","分单时间","初审工作性质","初审客户等级","终审工作性质","终审客户等级"};
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook("SheetName",title,list,null);
// 4 响应到客户端,弹出下载提示框
try {
this.setResponseHeader(response, "审核决策报表"+DateUtil.getString2Date(new Date())+".xls");
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("excel导出错误:"+e);
}
}else{
logger.error("无数据可导");
throw new RuntimeException("无数据可导");
}
}
/**
* 功能描述: 发送响应流方法
*/
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
logger.error("excel导出错误:"+e);
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
logger.error("excel导出错误:"+ex);
}
}
ExcelUtil :
public class ExcelUtil {
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param mapList 内容
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, List<BusinessReviewReportDto> list, HSSFWorkbook wb){
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(wb == null){
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
sheet.setColumnWidth(0, 25*256);
sheet.setColumnWidth(1, 25*256);
sheet.setColumnWidth(2, 25*256);
sheet.setColumnWidth(3, 25*200);
sheet.setColumnWidth(4, 25*200);
sheet.setColumnWidth(5, 25*200);
sheet.setColumnWidth(6, 25*200);
sheet.setColumnWidth(7, 25*200);
sheet.setColumnWidth(8, 25*200);
sheet.setColumnWidth(9, 25*200);
sheet.setColumnWidth(10, 25*200);
sheet.setColumnWidth(11, 25*200);
sheet.setColumnWidth(12, 25*200);
sheet.setColumnWidth(13, 25*200);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
//声明列对象
HSSFCell cell = null;
//创建标题
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
//创建内容
for (int i = 0;i<list.size();i++) {
XXXDto dto = list.get(i);
if (null!= dto) {
row = sheet.createRow(i + 1);
row.setRowStyle(style);
//将内容按顺序赋给对应的列对象
row.createCell(0).setCellValue(dto.getOrderCode()== null?"":dto.getOrderCode().toString());
row.createCell(1).setCellValue(dto.getTuiceScore()== null?"":dto.getTuiceScore().toString());
row.createCell(2).setCellValue(dto.getFirstSubmitPersonName()== null?"":dto.getFirstSubmitPersonName().toString());
row.createCell(3).setCellValue(dto.getFirstReasonValue()== null?"":dto.getFirstReasonValue().toString());
row.createCell(4).setCellValue(dto.getFirstChildReasonValue()== null?"":dto.getFirstChildReasonValue().toString());
row.createCell(5).setCellValue(dto.getPreDecisionRemark()== null?"":dto.getPreDecisionRemark().toString());
row.createCell(6).setCellValue(dto.getLastSubmitPersonName() == null?"":dto.getLastSubmitPersonName().toString());
row.createCell(7).setCellValue(dto.getLastReasonValue() == null?"":dto.getLastReasonValue().toString());
row.createCell(8).setCellValue(dto.getLastChildReasonValue()== null?"":dto.getLastChildReasonValue().toString());
row.createCell(9).setCellValue(dto.getLastDecisionRemark()== null?"":dto.getLastDecisionRemark().toString());
row.createCell(10).setCellValue(dto.getBystageAmount()== null?"":getStringAmount(dto.getBystageAmount()).toString());
row.createCell(11).setCellValue(dto.getFirstCreateTime()== null?"":DateUtil.getStringToDate2(dto.getFirstCreateTime()).toString());
row.createCell(12).setCellValue(dto.getLastCreateTime()== null?"":DateUtil.getStringToDate2(dto.getLastCreateTime()).toString());
row.createCell(13).setCellValue(dto.getDistributeTime()== null?"":DateUtil.getStringToDate2(dto.getDistributeTime()).toString());
row.createCell(14).setCellValue(dto.getPreDecisionJobLevel()== null?"":getStrJobLevel(dto.getPreDecisionJobLevel()).toString());
row.createCell(15).setCellValue(dto.getPreDecisionCustomerLevel()== null?"":getStrCustomerLevel(dto.getPreDecisionCustomerLevel()).toString());
row.createCell(16).setCellValue(dto.getLastDecisionJobLevel()== null?"":getStrJobLevel(dto.getLastDecisionJobLevel()).toString());
row.createCell(17).setCellValue(dto.getLastDecisionCustomerLevel()== null?"":getStrCustomerLevel(dto.getLastDecisionCustomerLevel()).toString());
}
}
return wb;
}
//客户等级
private static Object getStrCustomerLevel(Byte customerLevel) {
String str = "";
switch (customerLevel) {
case 1:
str = "A";
break;
case 2:
str = "B";
break;
case 3:
str = "C";
break;
case 4:
str = "D";
break;
default:
break;
}
return str;
}
public static String getStringAmount(Integer amount) {
if (amount != null) {
BigDecimal a = null;
a = BigDecimal.valueOf(amount.doubleValue() / 100);
return a.setScale(2, RoundingMode.HALF_UP).toPlainString();
} else {
return "";
}
}
}