@RequestMapping("/export")
public void export(HttpServletResponse response, HttpServletRequest request) {
List<String> headerLine = new ArrayList<>();
headerLine.add("id");
headerLine.add("price");
List<Object> objList = new ArrayList<>();
objList.add("001");
objList.add("1150");
List<Object> objList1 = new ArrayList<>();
objList1.add("002");
objList1.add("698");
List<List<Object>> content = new ArrayList<List<Object>>();
content.add(objList);
content.add(objList1);
HSSFWorkbook wb = exportObjectList(headerLine, content);
try {
OutputStream out = response.getOutputStream();
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.ms-excel");
String name = "导出Excel";
response.setHeader("Content-disposition", "attachment;filename="
+ new String(name.getBytes("utf-8"), "ISO-8859-1") + ".xls");
wb.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public HSSFWorkbook exportObjectList(List<String> headerLine, List<List<Object>> contentList) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow biaoTiTohang = sheet.createRow(0);
for (int i = 0; i < headerLine.size(); i++) {
biaoTiTohang.createCell(i).setCellValue(headerLine.get(i));
}
for (int i = 0; i < contentList.size(); i++) {
HSSFRow neiRongHang = sheet.createRow(i + 1);
List<Object> localList = contentList.get(i);
for (int j = 0; j < headerLine.size(); j++) {
Object temp;
if(j >= localList.size()) {
temp = "";
}else {
temp = localList.get(j);
}
if (temp instanceof Integer) {
int value = ((Integer) temp).intValue();
neiRongHang.createCell(j).setCellValue(value);
} else if (temp instanceof String) {
String value = (String) temp;
neiRongHang.createCell(j).setCellValue(value);
} else if (temp instanceof Double) {
double value = ((Double) temp).doubleValue();
neiRongHang.createCell(j).setCellValue(value);
} else if (temp instanceof Float) {
float value = ((Float) temp).floatValue();
neiRongHang.createCell(j).setCellValue(value);
} else if (temp instanceof Long) {
long value = ((Long) temp).longValue();
neiRongHang.createCell(j).setCellValue(value);
} else if (temp instanceof Boolean) {
boolean value = ((Boolean) temp).booleanValue();
neiRongHang.createCell(j).setCellValue(value);
} else if (temp instanceof Date) {
Date value = (Date) temp;
neiRongHang.createCell(j).setCellValue(value);
} else if (temp instanceof BigDecimal) {
double value = ((BigDecimal) temp).doubleValue();
neiRongHang.createCell(j).setCellValue(value);
} else{
if(null != temp){
String value = temp.toString();
neiRongHang.createCell(j).setCellValue(value);
}
}
}
}
return wb;
}
POI导出excel
最新推荐文章于 2024-12-03 14:20:06 发布