JSON数组转EXCEL,自定义动态生成表头
public static void createExcel(String[] heads,JSONArray jsonArray ,String uploadFileName) {
SXSSFWorkbook workbook = new SXSSFWorkbook();// 创建一个Excel文件
SXSSFSheet sheet = workbook.createSheet();// 创建一个Excel的Sheet
SXSSFRow titleRow = sheet.createRow(0);//创建表头
for(int i=0;i<heads.length;i++){//表头赋值
titleRow.createCell(i).setCellValue(heads[i]);
}
if (jsonArray.size() > 0) {//单元格赋值
for (int i = 0; i < jsonArray.size(); i++) {
SXSSFRow row = sheet.createRow(i + 1);
JSONObject json = jsonArray.getJSONObject(i); // 遍历 jsonarray
for(int j=0;j<heads.length;j++){
row.createCell(j).setCellValue(json.get(heads[j]).toString());//赋值
}
}
}
try {
// FileOutputStream fos = new FileOutputStream("D://ss.xls");
// workbook.write(fos);
// fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// public static void main(String[] args) { // String jsonStr = "[{\"NoPartySubIDs\":\"1\",\"ID\":\"齐商银行股份有限公司\",\"Typ\":\"124\"},{\"NoPartySubIDs\":\"2\",\"ID\":\"齐商银行\",\"Typ\":\"125\"}]"; // JSONArray json = JSONArray.fromObject(jsonStr); // String[] heads={"NoPartySubIDs","ID","Typ"}; // JSONConvertExcel s = new JSONConvertExcel(); // s.createExcel(heads,json,"债券"); // }