Java导出数据到Excel

1、设置模版,将Excel的数据域设置唯一的标识
2、Java后台
Workbook wb = null;
Row r = null;
Cell c = null;
String appKey = "";
String l = "";
try {
wb = new HSSFWorkbook(new FileInputStream(fcRegPath.toString() + fcRegFileName));
Sheet sheet = wb.getSheetAt(0);
Iterator<Row> rows = sheet.rowIterator();
// 遍历行
while (rows.hasNext()) {
r = rows.next();
Iterator<Cell> cells = r.cellIterator();
// 遍历列
while (cells.hasNext()) {
l = "";
c = cells.next();
// 取得需要替换的Cell
if (c.toString().indexOf("#") > -1) {
appKey = c.toString().replace("#", "");
String dataType = "";
// 数据类型转换
if (appKey.indexOf(":") > -1) {
String keyArray[] = appKey.split(":");
dataType = keyArray[0];
appKey = keyArray[1];
if (keyArray.length == 3) {
l = keyArray[2];
}
}
// 填充数据,json的key必须与模板的key一致
if (jsonNode.has(appKey) && "".equals(l)) {
setCellValue(c, jsonNode.get(appKey), dataType);
continue;
} else if (jsonNode.has(appKey) && !"".equals(l)) {
setCellValue(cells, c, jsonNode.get(appKey), dataType, l);
continue;
}
c.setCellValue("");
}
}
}

// 保存
FileOutputStream fileOut = new FileOutputStream(fcRegPath.toString() + fcRegFileName);
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
if (log.isErrorEnabled()) {
log.error("未找到文件!", e);
}
throw new SystemException(e, "未找到文件!");
} catch (IOException e) {
if (log.isErrorEnabled()) {
log.error("文档制作失败!", e);
}
throw new SystemException(e, "文档制作失败!");
}

你可能感兴趣的:(Excel)