JSON数组动态转EXCEL下载
把json数组动态的转换成excel下载下来
public static void jsonToXSSF(String str, HttpServletResponse response) throws IOException {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("mongo.xlsx", "UTF-8"));
try (XSSFWorkbook wb = new XSSFWorkbook();
OutputStream output = response.getOutputStream()) {
XSSFSheet sheet = wb.createSheet("mongo");
Map<String, Integer> titles = new HashMap<>();
int rowNo = 1;
int cellMax = 0;
int celltitleNo = 0;
JSONArray jsonArray = JSONArray.parseArray(str);
XSSFRow rowtitle = sheet.createRow(0);
for (Object item : jsonArray) {
JSONObject jsonObject = (JSONObject) item;
Set<String> keys = jsonObject.keySet();
XSSFRow row = sheet.createRow(rowNo++);
cellMax = Math.max((keys.size() - 1), cellMax);
for (String key : keys) {
if (!titles.containsKey(key)) {
titles.put(key, celltitleNo++);
XSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
XSSFCell celltitle = rowtitle.createCell(titles.get(key));
celltitle.setCellStyle(cellStyle);
celltitle.setCellValue(key);
}
XSSFCell cell = row.createCell(titles.get(key));
if (jsonObject.get(key) instanceof Double) {
cell.setCellValue(jsonObject.getDouble(key));
} else if (jsonObject.get(key) instanceof Integer) {
cell.setCellValue(jsonObject.getInteger(key));
} else if (jsonObject.get(key) instanceof Date) {
cell.setCellValue(jsonObject.getDate(key));
} else if (jsonObject.get(key) instanceof Boolean) {
cell.setCellValue(jsonObject.getBoolean(key));
} else {
cell.setCellValue(jsonObject.getString(key));
}
}
}
sheet.setAutoFilter(new CellRangeAddress(0, rowNo, 0, cellMax));
wb.write(output);
}
}
|