Maven依赖(此处为本人所用的)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
ExcelExportUtil导出工具(直接复制可用)
/** * Excel表格导出工具类 * @author ypl * */
public class ExcelExportUtil {
private static Logger logger = Logger.getLogger(ExcelExportUtil.class);
/** * 获取封装好数据的 HSSFWorkbook * @param list 内容数据(map中key对应headRow的每一个头,value为对应的值) * @param headRowList 头行标题的集合 * @param tableName 表标题 * @param widthMap 各列列宽(map中 key:指定列(从0开始),value:宽度(一般3-4个字符:16,时间类型+分秒:25)) * @param response * @throws IOException */
public static void generateExcel(List<Map<String, String>> list, String tableName, Map<Integer,Integer> widthMap, HttpServletResponse response) throws IOException {
if (list == null || list.isEmpty()) {
logger.info("要导出的数据列为空");
return;
}
if (StringUtils.isBlank(tableName)) {
logger.info("要导出的表名为空");
return;
}
List<String> headRowList = new ArrayList<>(14);
Set<String> keySet = list.get(0).keySet();
for (String key : keySet) {
headRowList.add(key);
}
if (headRowList == null || headRowList.isEmpty()) {
logger.info("要导出的数据表头行为空");
return;
}
logger.info("getexcel start");
HSSFWorkbook book = new HSSFWorkbook();
OutputStream outputStream = null;
try{
HSSFSheet sheet = book.createSheet(tableName);
if(widthMap!=null && widthMap.size()>0){
setByWidthMap(sheet, widthMap);
}else {
setDefaultSheetWidth(sheet,headRowList.size());
}
HSSFCellStyle style = book.createCellStyle();
setStyle(style);
HSSFFont font = book.createFont();
setFont(style, font, 22, "宋体");
HSSFCellStyle bodyStyle = book.createCellStyle();
setStyle(bodyStyle);
bodyStyle.setWrapText(true);
HSSFCellStyle headstyle = book.createCellStyle();
setStyle(headstyle);
HSSFFont headfont = book.createFont();
setFont(headstyle, headfont, 11, null);
outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/msexcel");
response.setHeader("Content-disposition","attachment;filename=\"" + new String(
(java.net.URLEncoder.encode(tableName + CommonUtils.getNowDateStringOf8() + (int) (Math.random() * 100) + ".xls", "UTF-8")).getBytes("UTF-8"),"GB2312") + "\"");
int colSize = list.get(0).entrySet().size();
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, colSize-1));
HSSFRow firstRow = sheet.createRow(0);
HSSFCell firstCell = firstRow.createCell(0);
firstCell.setCellValue(tableName);
firstCell.setCellStyle(style);
HSSFRow headRow = sheet.createRow(1);
headRow.setHeight((short) (20 * 20));
for (int i = 0; i < headRowList.size(); i++) {
HSSFCell cell = headRow.createCell(i);
cell.setCellValue(headRowList.get(i));
cell.setCellStyle(headstyle);
}
for(int i=0; i<list.size(); i++) {
HSSFRow row2 = sheet.createRow(i+2);
row2.setHeight((short) (25 * 20));
Map<String, String> map = list.get(i);
for(int j=0; j<headRowList.size(); j++) {
String value = map.get(headRowList.get(j));
HSSFCell cell = row2.createCell(j);
cell.setCellValue(value);
cell.setCellStyle(bodyStyle);
}
}
book.write(outputStream);
outputStream.flush();
outputStream.close();
} catch(Exception e) {
logger.error("jftj/genexcel Exception", e);
} finally {
if (outputStream != null) {
outputStream.close();
}
logger.info("getexcel end");
}
}
/** * 字体设置 * @param style * @param font */
private static void setFont(HSSFCellStyle style, HSSFFont font, int size, String fontName) {
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontHeightInPoints((short) size);
if(StringUtils.isNotBlank(fontName)){
font.setFontName(fontName);
}
style.setFont(font);
}
/** * 根据widthMap设置相应的列宽 * @param sheet * @param widthMap */
private static void setByWidthMap(HSSFSheet sheet, Map<Integer, Integer> widthMap) {
for (Entry<Integer, Integer> entry : widthMap.entrySet()) {
sheet.setColumnWidth(entry.getKey(), entry.getValue() * 256);
}
}
/** * 默认宽度设置 * 3-4个中文字符 16 * 时间类型 ,带时分秒的 25 * @param sheet * @param len */
private static void setDefaultSheetWidth(HSSFSheet sheet, int len) {
for (int i = 0; i < len; i++) {
sheet.setColumnWidth(i, 25 * 256);
}
}
/** * 私密直播单元格宽度设置 * @param sheet */
private static void setStyle(HSSFCellStyle style) {
style.setFillForegroundColor(HSSFColor.WHITE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
}
}
导出Controller
/** * 导出检验 * * @param request * @param response * @param customer * @throws Exception */
@RequestMapping(value = "/checkExport", method = RequestMethod.GET)
public void checkExport(String searchText, String beginTime, String endTime, Integer orderStatus, String objectId, Integer orderSource, Integer productId, Integer payPlatForm,
Integer payType,HttpServletRequest request, HttpServletResponse response) throws Exception {
int count = payServiceRemoting.countXsbOrderMng(searchText, beginTime, endTime, orderStatus, objectId, orderSource, productId, payPlatForm, payType);
if (count >10000) {
putFailedResult(response, "导出数据超过10000条");
return;
}
if (count == 0) {
putFailedResult(response, "导出数据超过为空");
return;
}
putSuccessResult(response, "操作成功");
return;
}
/** * 导出 * @param model * @param applyLiveStatus * @param searchkey * @param pageNo * @param pageSize * @param request * @param response * @return * @throws IOException */
@RequestMapping(value = "exportExcel",method = RequestMethod.GET)
public void exportExcel(String searchText, String beginTime, String endTime, Integer orderStatus, String objectId, Integer orderSource, Integer productId, Integer payPlatForm,
Integer payType,HttpServletRequest request, HttpServletResponse response) throws IOException {
List<XsbOrderVo> orderVos = payServiceRemoting.listXsbOrderMng(searchText, beginTime, endTime, orderStatus, objectId, orderSource, productId, payPlatForm, payType,null, null);
List<Map<String, String>> data = new ArrayList<>();
for (XsbOrderVo xsbOrderVo : orderVos) {
Map<String, String> map = new LinkedHashMap<>();
map.put("订单编号", xsbOrderVo.getOrderId());
map.put("服务类型", xsbOrderVo.getOrderSource());
map.put("项目名称", xsbOrderVo.getObjectName());
map.put("姓名", xsbOrderVo.getCustomerName());
map.put("手机", xsbOrderVo.getCustomerPhone());
map.put("支付方式", xsbOrderVo.getPayType());
map.put("付款金额(/元)", xsbOrderVo.getOrderAmount());
map.put("支付状态", xsbOrderVo.getOrderStatus());
map.put("订单来源", xsbOrderVo.getPayPlatForm());
map.put("下单时间", xsbOrderVo.getCreateTime());
data.add(map);
}
Map<Integer,Integer> widthMap = new HashMap<>();
widthMap.put(0, 20);
widthMap.put(1, 25);
widthMap.put(2, 25);
widthMap.put(3, 20);
widthMap.put(4, 20);
widthMap.put(5, 25);
widthMap.put(6, 25);
widthMap.put(7, 20);
widthMap.put(8, 20);
widthMap.put(9, 22);
ExcelExportUtil.generateExcel(data, "xxxx",widthMap response);
}
页面
//页面
<form action="List.do" id="searchForm" style="width:100%;">
...
<form/>
<button type="button" class="btn btn-success mb5" style="float:right;" id = "exportExcel">导出项目列表</button>
//导出excel
$('#exportExcel').on('click',function(){
var isCheck=false;
var formData = $('#searchForm').serialize();
$.ajax({
type: "GET",
url: "/checkExport",
async: false,
dataType:"json",
data: formData,
success: function(data) {
if (data.status == '1') {
isCheck=true;
} else {
alert(data.msg);
};
},
error : function() {
alert("下载失败");
}
})
if(isCheck){
parent.location.href="/exportExcel?"+formData;
}
})