- /**
- * 构建excel
- * @param block 闭包,封装构建逻辑
- */
- def build(dataList,titleList,out,Closure block){
- def wb = new HSSFWorkbook();
- def sheet = wb.createSheet("new sheet");
- def row
- def cell
- def style = wb.createCellStyle()
- def font = wb.createFont()
- font.setFontHeightInPoints((short)12)
- font.setFontName("宋体")
- font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD)
- style.setFont(font)
- style.setAlignment(HSSFCellStyle.ALIGN_CENTER)
- style.setFillBackgroundColor(HSSFColor.ORANGE.index)
- row = sheet.createRow((short) 0);
- titleList.eachWithIndex{title, i ->
- cell = row.createCell((short) (i));
- cell.setCellStyle(style)
- cell.setCellValue(title);
- }
- //生成逻辑
- block.call(sheet,row)
- titleList.size().times{ i ->
- sheet.autoSizeColumn((short)i)
- }
- wb.write(out);
- out.close()
- }
- /**
- * 生成excel
- * @param dataList 数据列表,其中的元素是放入每行cell的数据
- * @param titleList 标题列表
- * @param out
- */
- def genForList(List<List> dataList,List titleList,out){
- def block = { sheet,row ->
- dataList.eachWithIndex{ dataRow,i ->
- row = sheet.createRow((short) (i+1));
- dataRow.eachWithIndex{ data,j ->
- row.createCell((short) (j)).setCellValue(data.toString())
- }
- }
- }
- build(dataList,titleList,out,block)
- }
- /**
- * 生成excel
- * @param dataList 数据列表,其中的元素是放入每行cell的数据
- * @param titleList 标题列表
- * @param outOutputStream
- */
- def genForMap(List<Map> dataList,List titleList,out){
- def block = { sheet,row ->
- dataList.eachWithIndex{ dataRow,i ->
- row = sheet.createRow((short) (i+1));
- dataRow.eachWithIndex{ k,v,j ->
- row.createCell((short) (j)).setCellValue(v.toString())
- }
- }
- }
- build(dataList,titleList,out,block)
- }
- //该片段来自于http://www.codesnippet.cn/detail/16112012413.html
来源: http://www.codesnippet.cn/detail/16112012413.html