POI导出excel,对于所有的VO实体都通用.

POI导出excel,,对于所有的VO实体都通用.

分类:java

/* 前面是列定义,后面是VO属性* para :主管海关,自定义类型,内部清单号-customMasterLabel,entryTypeLabel,internalListNo* list : 数据list<VO>* */public static String commonExport(String para,List list) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{HttpServletResponse response = ServletActionContext.getResponse();/** POI 操作Excel – 步骤:* */HSSFWorkbook workbook = new HSSFWorkbook();ServletOutputStream out = null;try {out = response.getOutputStream();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}HSSFSheet sheet = workbook.createSheet("sheet1");sheet.setColumnWidth(0, 1500); //设置序号列宽,其他列暂时一样宽sheet.setDefaultColumnWidth ((short)12);// 设置工作表列宽sheet.setDefaultRowHeight((short)250);// 设置工作表行高/** sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 – 在下面 – 可扩展】* *///HSSFCellStyle columnTopStyle = ExportExcelUtilsStyle.getColumnTopStyle(workbook);//获取列头样式对象//HSSFCellStyle style = ExportExcelUtilsStyle.getStyle(workbook);//单元格样式对象//列头数组定义para = "序号,"+para;String[] s = para.split("-");String s0 = s[0];String s1 = s[1];List titleList = Arrays.asList(s0.split(","));List colList = Arrays.asList(s1.split(","));//String[] label = ExportExcelUtilsModel.getExportMoedel(modelFlag);// 定义所需列数int columnNum = titleList.size();//设置列头HSSFRow row1 = sheet.createRow((short)0);// 在索引0的位置创建行(最顶端的行)HSSFCell cell1 = null;// 在索引0的位置创建单元格(左上端)// 将列头设置到sheet的单元格中for(int n=0;n<columnNum;n++){cell1 = row1.createCell((short)(n));//创建列头对应个数的单元格cell1.setCellType(HSSFCell.CELL_TYPE_STRING);//设置列头单元格的数据类型cell1.setCellValue(titleList.get(n).toString());//设置列头单元格的值//cell1.setCellStyle(columnTopStyle);//设置列头单元格样式}if(null==list||list.size()==0){return "exportList size is zero";}int i=1;for(int m=0;m<list.size();m++){StringBuffer sb = new StringBuffer();String result="";for(int k=0;k<colList.size();k++){result = BeanUtils.getProperty(list.get(m),colList.get(k).toString());if(k==0){sb.append(result);}else{sb.append(","+result);}}//将属性转化成字符串数组的格式以便于写到sheet中String contentStr = i+","+sb.toString();List c = Arrays.asList(contentStr.split(","));//创建行(从下面的i+1要注意,第0行是列头,因此创建新行要从下一行开始)HSSFRow row = sheet.createRow(i);//创建所需的行数for(short j=0;j<columnNum;j++){HSSFCell cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);//设置单元格的数据类型cell.setCellValue(c.get(j).toString());//设置单元格的值//cell.setCellStyle(style);//设置单元格样式}i++;}if(workbook !=null){// 获取当前时间用作文件名try {String filename = "导出文件的名字" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());response.setContentType("application/ms-excel");response.setHeader("Content-Disposition", "filename="+new String(filename.toString().concat(".xls").getBytes(),"UTF-8"));workbook.write(out);out.flush();// 缓冲out.close();// 关闭流(养成好的习惯打开了就别忘记关闭)} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return "导出成功";}

版权声明:本文为博主原创文章,未经博主允许不得转载。

上一篇JQuery中 attr 详解

顶0踩0

爱情使人忘记时间,时间也使人忘记爱情。

POI导出excel,对于所有的VO实体都通用.

相关文章:

你感兴趣的文章:

标签云: