javaEE实现简单的导出excel功能

该代码为按照指定excel模板导出数据为excel的简单Demo


//获取需要导出的excel模板路径  : confilg/temp目录下

public static final String TEMPLATE_PATH =MyController.class.getClassLoader().getResource("config/temp/").getPath();

@RequestMapping(value="/exportToExcel.do",produces = "application/josn;charset=UTF-8")
public void exportToExcel(HttpServletResponse response){
try {
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("excel导出结   果"+".xls", "UTF-8"));
ServletOutputStream outputStream = response.getOutputStream();
exportToExcel(outputStream);
} catch (Exception e) {
e.printStackTrace();

}


public boolean exportToExcel(ServletOutputStream outputStream) {

//模拟一组需要导出的数据

List<Item> data = new ArrayList<Item>();

try{
FileInputStream in = new FileInputStream(new File(TEMPLATE_PATH+"MB.xls"));
HSSFWorkbook work = new HSSFWorkbook(in);
HSSFSheet sheet = work.getSheetAt(0);

for (int i=0 ; i

GlxxRyExportVo ryxx = data.get(i);

//创建空白行,从第 i 行开始填充数据
Row contentRow = (Row) sheet.createRow(i);

//创建5列

Cell cell0 = contentRow.createCell(0);
Cell cell1 = contentRow.createCell(1);
Cell cell2 = contentRow.createCell(2);
Cell cell3 = contentRow.createCell(3);
Cell cell4 = contentRow.createCell(4);

//给第 i 行的每一列填充数据
cell0.setCellValue(String.valueOf(i+1));
cell1.setCellValue(Item.getElement1());
cell2.setCellValue(Item.getElement2());
cell3.setCellValue(Item.getElement3());
cell4.setCellValue(Item.getElement4());

}
work.write(outputStream);
return true;
}catch (IOException e) {
return false;
}
}

所需jar包:


            org.apache.poi
            poi-ooxml
            3.16


你可能感兴趣的:(java)