Apache POI 实现Excel文件单元格合并、冻结和文件导出

来源:互联网 发布:软件研发中心简介 编辑:程序博客网 时间:2024/05/29 09:31
                  //经常用到poi导出excel操作,所以留几行代码,以备他日之需
Workbook wb = new HSSFWorkbook();Sheet sheet = wb.createSheet("sheet1");Row row = null;Cell cell = null;//创建表头单元格样式CellStyle cs_header = wb.createCellStyle();Font boldFont = wb.createFont();boldFont.setFontName("Consolas");boldFont.setFontHeightInPoints((short)14);cs_header.setFont(boldFont);cs_header.setBorderBottom((short)1);cs_header.setBorderLeft((short)1);cs_header.setBorderRight((short)1);cs_header.setBorderTop((short)1);//第一行,时间row = sheet.createRow((short)0);row.setHeightInPoints((short)24);createMultiCell(row,cell,cs_header,0,31,"访问日期:"+time1+" to "+time2);//第二行,大标题row = sheet.createRow((short)1);row.setHeightInPoints((short)24);createMultiCell(row,cell,cs_header,0,6," ");createMultiCell(row,cell,cs_header,6,25,"访问路径");//第三行,列标题row = sheet.createRow((short)2);row.setHeightInPoints((short)24);String[] headers = new String[]{"访问时间","地域","来源","关键字","进入页","停留时间","访问页数","1时间","1停留","1页面","2时间","2停留","2页面","3时间","3停留","3页面","4时间","4停留","4页面","5时间","5停留","5页面","6时间","6停留","6页面","7时间","7停留","7页面","8时间","8停留","8页面"};for(int i=0; i<headers.length; i++){cell = row.createCell((short)i);cell.setCellValue(headers[i]);cell.setCellStyle(cs_header);}//创建文本单元格样式CellStyle cs_text = wb.createCellStyle();Font textFont = wb.createFont();textFont.setFontName("Consolas");textFont.setFontHeightInPoints((short)10);cs_text.setFont(textFont);cs_text.setBorderBottom((short)1);cs_text.setBorderLeft((short)1);cs_text.setBorderRight((short)1);cs_text.setBorderTop((short)1);//将数据写入表格for(int i=0; i<list.size(); i++){row = sheet.createRow((short)(i+3));Object[] rw = list.get(i);for(int j=0; j<rw.length; j++){cell = row.createCell((short)j);cell.setCellValue(rw[j].toString());cell.setCellStyle(cs_text);}}//合并第1行1-32列sheet.addMergedRegion(new CellRangeAddress((short)0, (short)0, (short)0, (short)31));//合并第2行1-6列sheet.addMergedRegion(new CellRangeAddress((short)1, (short)1, (short)0, (short)6));//合并第2行7-32行sheet.addMergedRegion(new CellRangeAddress((short)1, (short)1, (short)7, (short)31));//冻结7X3(宽,高)区域中的单元格sheet.createFreezePane(7, 3);try {//将workbook写到输入流(下载时候,这个输出流可能是ServletOutStream,写入文件是FileOutputStream,等等)wb.write(os);} catch (IOException e) {e.printStackTrace();}


原创粉丝点击