Skip to content

Instantly share code, notes, and snippets.

@jecyhw
Last active May 16, 2017 07:24
Show Gist options
  • Save jecyhw/0c1967e9950cd566a523e286dc89a80b to your computer and use it in GitHub Desktop.
Save jecyhw/0c1967e9950cd566a523e286dc89a80b to your computer and use it in GitHub Desktop.
poi创建excel示例
public void exportProj(HttpServletResponse response) {
HSSFWorkbook workbook = new HSSFWorkbook();
final List<String> headers = new ArrayList<>();
headers.add("列1");
headers.add("列2");
headers.add("列3");
headers.add("列4");
Map<Integer, JSONArray> map;
for (Integer cityId : map.keySet()) {
JSONArray projs = map.get(cityId);
HSSFSheet sheet = workbook.createSheet(cityInfoMap.get(cityId).getCityName());
int rowNum = 0;
//设置标题行
HSSFRow row = sheet.createRow(rowNum++);
for (int i = 0; i < headers.size(); ++i) {
HSSFCell cell = row.createCell(i, CellType.STRING);
cell.setCellValue(headers.get(i));
}
//填充数据行
for (Object proj : projs) {
ProjToExport export = (ProjToExport)proj;
row = sheet.createRow(rowNum++);
List<String> values = new ArrayList<>(headers.size());
values.add(export.getGroupId().toString());
values.add(export.getProjName());
values.add(export.getProjName())
values.add(export.getTargetPhone());
for (int i = 0; i < values.size(); ++i) {
HSSFCell cell = row.createCell(i, CellType.STRING);
cell.setCellValue(values.get(i));
}
}
for (int i = 0; i < headers.size(); ++i) {
sheet.autoSizeColumn(i);
}
}
//设置文件名
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=" + "export_" + DateFormatUtils.format(new Date(), "yyyy-MM-dd") + ".xls");
try {
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment