Excel 操作 POI




1 先来看一下HSSFBOOK的一些基本操作,样式

public ActionResult excelPrint() {  
    HSSFWorkbook workbook = new HSSFWorkbook();// 创建一个Excel文件  
    HSSFSheet sheet = workbook.createSheet();// 创建一个Excel的Sheet  
    sheet.createFreezePane(1, 3);// 冻结  
    // 设置列宽  
    sheet.setColumnWidth(0, 1000);  
    sheet.setColumnWidth(1, 3500);  
    sheet.setColumnWidth(2, 3500);  
    sheet.setColumnWidth(3, 6500);  
    sheet.setColumnWidth(4, 6500);  
    sheet.setColumnWidth(5, 6500);  
    sheet.setColumnWidth(6, 6500);  
    sheet.setColumnWidth(7, 2500);  
    // Sheet样式  
    HSSFCellStyle sheetStyle = workbook.createCellStyle();  
    // 背景色的设定  
    sheetStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);  
    // 前景色的设定  
    sheetStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);  
    // 填充模式  
    sheetStyle.setFillPattern(HSSFCellStyle.FINE_DOTS);  
    // 设置列的样式  
    for (int i = 0; i <= 14; i++) {  
      sheet.setDefaultColumnStyle((short) i, sheetStyle);  
    }  
    // 设置字体  
    HSSFFont headfont = workbook.createFont();  
    headfont.setFontName("黑体");  
    headfont.setFontHeightInPoints((short) 22);// 字体大小  
    headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗  
    // 另一个样式  
    HSSFCellStyle headstyle = workbook.createCellStyle();  
    headstyle.setFont(headfont);  
    headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
    headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中  
    headstyle.setLocked(true);  
    headstyle.setWrapText(true);// 自动换行  
    // 另一个字体样式  
    HSSFFont columnHeadFont = workbook.createFont();  
    columnHeadFont.setFontName("宋体");  
    columnHeadFont.setFontHeightInPoints((short) 10);  
    columnHeadFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
    // 列头的样式  
    HSSFCellStyle columnHeadStyle = workbook.createCellStyle();  
    columnHeadStyle.setFont(columnHeadFont);  
    columnHeadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
    columnHeadStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中  
    columnHeadStyle.setLocked(true);  
    columnHeadStyle.setWrapText(true);  
    columnHeadStyle.setLeftBorderColor(HSSFColor.BLACK.index);// 左边框的颜色  
    columnHeadStyle.setBorderLeft((short) 1);// 边框的大小  
    columnHeadStyle.setRightBorderColor(HSSFColor.BLACK.index);// 右边框的颜色  
    columnHeadStyle.setBorderRight((short) 1);// 边框的大小  
    columnHeadStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体  
    columnHeadStyle.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色  
    // 设置单元格的背景颜色(单元格的样式会覆盖列或行的样式)  
    columnHeadStyle.setFillForegroundColor(HSSFColor.WHITE.index);  
  
    HSSFFont font = workbook.createFont();  
    font.setFontName("宋体");  
    font.setFontHeightInPoints((short) 10);  
    // 普通单元格样式  
    HSSFCellStyle style = workbook.createCellStyle();  
    style.setFont(font);  
    style.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 左右居中  
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 上下居中  
    style.setWrapText(true);  
    style.setLeftBorderColor(HSSFColor.BLACK.index);  
    style.setBorderLeft((short) 1);  
    style.setRightBorderColor(HSSFColor.BLACK.index);  
    style.setBorderRight((short) 1);  
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体  
    style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色.  
    style.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色.  
    // 另一个样式  
    HSSFCellStyle centerstyle = workbook.createCellStyle();  
    centerstyle.setFont(font);  
    centerstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
    centerstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中  
    centerstyle.setWrapText(true);  
    centerstyle.setLeftBorderColor(HSSFColor.BLACK.index);  
    centerstyle.setBorderLeft((short) 1);  
    centerstyle.setRightBorderColor(HSSFColor.BLACK.index);  
    centerstyle.setBorderRight((short) 1);  
    centerstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体  
    centerstyle.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色.  
    centerstyle.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色.  
  
    try {  
      // 创建第一行  
      HSSFRow row0 = sheet.createRow(0);  
      // 设置行高  
      row0.setHeight((short) 900);  
      // 创建第一列  
      HSSFCell cell0 = row0.createCell(0);  
      cell0.setCellValue(new HSSFRichTextString("中非发展基金投资项目调度会工作落实情况对照表"));  
      cell0.setCellStyle(headstyle);  
      /** 
       * 合并单元格 
       *    第一个参数:第一个单元格的行数(从0开始) 
       *    第二个参数:第二个单元格的行数(从0开始) 
       *    第三个参数:第一个单元格的列数(从0开始) 
       *    第四个参数:第二个单元格的列数(从0开始) 
       */  
      CellRangeAddress range = new CellRangeAddress(0, 0, 0, 7);  
      sheet.addMergedRegion(range);  
      // 创建第二行  
      HSSFRow row1 = sheet.createRow(1);  
      HSSFCell cell1 = row1.createCell(0);  
      cell1.setCellValue(new HSSFRichTextString("本次会议时间:2009年8月31日       前次会议时间:2009年8月24日"));  
      cell1.setCellStyle(centerstyle);  
      // 合并单元格  
      range = new CellRangeAddress(1, 2, 0, 7);  
      sheet.addMergedRegion(range);  
      // 第三行  
      HSSFRow row2 = sheet.createRow(3);  
      row2.setHeight((short) 750);  
      HSSFCell cell = row2.createCell(0);  
      cell.setCellValue(new HSSFRichTextString("责任者"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(1);  
      cell.setCellValue(new HSSFRichTextString("成熟度排序"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(2);  
      cell.setCellValue(new HSSFRichTextString("事项"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(3);  
      cell.setCellValue(new HSSFRichTextString("前次会议要求\n/新项目的项目概要"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(4);  
      cell.setCellValue(new HSSFRichTextString("上周工作进展"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(5);  
      cell.setCellValue(new HSSFRichTextString("本周工作计划"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(6);  
      cell.setCellValue(new HSSFRichTextString("问题和建议"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(7);  
      cell.setCellValue(new HSSFRichTextString("备 注"));  
      cell.setCellStyle(columnHeadStyle);  
      // 访问数据库,得到数据集  
      List<DeitelVO> deitelVOList = getEntityManager().queryDeitelVOList();  
      int m = 4;  
      int k = 4;  
      for (int i = 0; i < deitelVOList.size(); i++) {  
        DeitelVO vo = deitelVOList.get(i);  
        String dname = vo.getDname();  
        List<Workinfo> workList = vo.getWorkInfoList();  
        HSSFRow row = sheet.createRow(m);  
        cell = row.createCell(0);  
        cell.setCellValue(new HSSFRichTextString(dname));  
        cell.setCellStyle(centerstyle);  
        // 合并单元格  
        range = new CellRangeAddress(m, m + workList.size() - 1, 0, 0);  
        sheet.addMergedRegion(range);  
        m = m + workList.size();  
  
        for (int j = 0; j < workList.size(); j++) {  
          Workinfo w = workList.get(j);  
          // 遍历数据集创建Excel的行  
          row = sheet.getRow(k + j);  
          if (null == row) {  
            row = sheet.createRow(k + j);  
          }  
          cell = row.createCell(1);  
          cell.setCellValue(w.getWnumber());  
          cell.setCellStyle(centerstyle);  
          cell = row.createCell(2);  
          cell.setCellValue(new HSSFRichTextString(w.getWitem()));  
          cell.setCellStyle(style);  
          cell = row.createCell(3);  
          cell.setCellValue(new HSSFRichTextString(w.getWmeting()));  
          cell.setCellStyle(style);  
          cell = row.createCell(4);  
          cell.setCellValue(new HSSFRichTextString(w.getWbweek()));  
          cell.setCellStyle(style);  
          cell = row.createCell(5);  
          cell.setCellValue(new HSSFRichTextString(w.getWtweek()));  
          cell.setCellStyle(style);  
          cell = row.createCell(6);  
          cell.setCellValue(new HSSFRichTextString(w.getWproblem()));  
          cell.setCellStyle(style);  
          cell = row.createCell(7);  
          cell.setCellValue(new HSSFRichTextString(w.getWremark()));  
          cell.setCellStyle(style);  
        }  
        k = k + workList.size();  
      }  
      // 列尾  
      int footRownumber = sheet.getLastRowNum();  
      HSSFRow footRow = sheet.createRow(footRownumber + 1);  
      HSSFCell footRowcell = footRow.createCell(0);  
      footRowcell.setCellValue(new HSSFRichTextString("                    审  定:XXX      审  核:XXX     汇  总:XX"));  
      footRowcell.setCellStyle(centerstyle);  
      range = new CellRangeAddress(footRownumber + 1, footRownumber + 1, 0, 7);  
      sheet.addMergedRegion(range);  
  
      HttpServletResponse response = getResponse();  
      HttpServletRequest request = getRequest();  
      String filename = "未命名.xls";//设置下载时客户端Excel的名称  
      // 请见:http://zmx.iteye.com/blog/622529  
      filename = Util.encodeFilename(filename, request);  
      response.setContentType("application/vnd.ms-excel");  
      response.setHeader("Content-disposition", "attachment;filename=" + filename);  
      OutputStream ouputStream = response.getOutputStream();  
      workbook.write(ouputStream);  
      ouputStream.flush();  
      ouputStream.close();  
  
    } catch (Exception e) {  
      e.printStackTrace();  
    }  
    return null;  
  }  


-----------------------------------------------------------------------------

2 POI的一些方法

一、 POI简介

            Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

二、 HSSF概况

            HSSF 是Horrible SpreadSheet Format的缩写,通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。

三、 POI EXCEL文档结构类

            HSSFWorkbook excel文档对象

            HSSFSheet excel的sheet HSSFRow excel的行

            HSSFCell excel的单元格 HSSFFont excel字体

            HSSFName 名称 HSSFDataFormat 日期格式

            HSSFHeader sheet头

            HSSFFooter sheet尾

            HSSFCellStyle cell样式

            HSSFDateUtil 日期

            HSSFPrintSetup 打印

            HSSFErrorConstants 错误信息表

四、 EXCEL常用操作方法

  1、 得到Excel常用对象           
  1. POIFSFileSystem fs=newPOIFSFileSystem(new FileInputStream("d:/test.xls"));   
  2. //得到Excel工作簿对象    
  3. HSSFWorkbook wb new HSSFWorkbook(fs);  
  4. //得到Excel工作表对象    
  5. HSSFSheet sheet wb.getSheetAt(0);   
  6. //得到Excel工作表的行    
  7. HSSFRow row sheet.getRow(i);  
  8. //得到Excel工作表指定行的单元格    
  9. HSSFCell cell row.getCell((short) j);  
  10. cellStyle cell.getCellStyle();//得到单元格样式  
 2、建立Excel常用对象
  1. HSSFWorkbook wb new HSSFWorkbook();//创建Excel工作簿对象   
  2. HSSFSheet sheet wb.createSheet("new sheet");//创建Excel工作表对象     
  3. HSSFRow row sheet.createRow((short)0); //创建Excel工作表的行   
  4. cellStyle wb.createCellStyle();//创建单元格样式   
  5. row.createCell((short)0).setCellStyle(cellStyle); //创建Excel工作表指定行的单元格   
  6. row.createCell((short)0).setCellValue(1); //设置Excel工作表的值  
3、设置sheet名称和单元格内容
  1. wb.setSheetName(1, "第一张工作表",HSSFCell.ENCODING_UTF_16);          
  2. cell.setEncoding((short) 1);      
  3. cell.setCellValue("单元格内容");  
4、取得sheet的数目 
  1. wb.getNumberOfSheets()   
5、  根据index取得sheet对象
  1. HSSFSheet sheet wb.getSheetAt(0);  
6、取得有效的行数
  1. int rowcount sheet.getLastRowNum();  
7、取得一行的有效单元格个数
  1. row.getLastCellNum();    

8、单元格值类型读写

 

[c-sharp]   view plain copy print ?
  1. cell.setCellType(HSSFCell.CELL_TYPE_STRING); //设置单元格为STRING类型   
  2. cell.getNumericCellValue();//读取为数值类型的单元格内容  

 

 

 

9、设置列宽、行高

 

[c-sharp]   view plain copy print ?
  1. sheet.setColumnWidth((short)column,(short)width);      
  2. row.setHeight((short)height);    

 

 

 

10、添加区域,合并单元格

 

[c-sharp]   view plain copy print ?
  1. Region region new Region((short)rowFrom,(short)columnFrom,(short)rowTo  
  2. ,(short)columnTo);//合并从第rowFrom行columnFrom列   
  3. sheet.addMergedRegion(region);// 到rowTo行columnTo的区域      
  4. //得到所有区域       
  5. sheet.getNumMergedRegions()   

 

 

 

11、保存Excel文件

 

[c-sharp]   view plain copy print ?
  1. FileOutputStream fileOut new FileOutputStream(path);   
  2. wb.write(fileOut);   

 

 

 

12、根据单元格不同属性返回字符串数值

 

[c-sharp]   view plain copy print ?
  1. public String getCellStringValue(HSSFCell cell)      
  2.         String cellValue "";      
  3.         switch (cell.getCellType())      
  4.         case HSSFCell.CELL_TYPE_STRING://字符串类型   
  5.             cellValue cell.getStringCellValue();      
  6.             if(cellValue.trim().equals("")||cellValue.trim().length()<=0)      
  7.                 cellValue=" ";      
  8.             break;      
  9.         case HSSFCell.CELL_TYPE_NUMERIC: //数值类型   
  10.             cellValue String.valueOf(cell.getNumericCellValue());      
  11.             break;      
  12.         case HSSFCell.CELL_TYPE_FORMULA: //公式   
  13.             cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);      
  14.             cellValue String.valueOf(cell.getNumericCellValue());      
  15.             break;      
  16.         case HSSFCell.CELL_TYPE_BLANK:      
  17.             cellValue=" ";      
  18.             break;      
  19.         case HSSFCell.CELL_TYPE_BOOLEAN:      
  20.             break;      
  21.         case HSSFCell.CELL_TYPE_ERROR:      
  22.             break;      
  23.         default:      
  24.             break;      
  25.              
  26.         return cellValue;      
  27.         

 

 

 

13、常用单元格边框格式

 

[c-sharp]   view plain copy print ?
  1. HSSFCellStyle style wb.createCellStyle();      
  2. style.setBorderBottom(HSSFCellStyle.BORDER_DOTTED);//下边框        
  3. style.setBorderLeft(HSSFCellStyle.BORDER_DOTTED);//左边框        
  4. style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框        
  5. style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框    

 

 

 

14、设置字体和内容位置

 

[c-sharp]   view plain copy print ?
  1. HSSFFont  wb.createFont();      
  2. f.setFontHeightInPoints((short) 11);//字号       
  3. f.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//加粗       
  4. style.setFont(f);      
  5. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中       
  6. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中       
  7. style.setRotation(short rotation);//单元格内容的旋转的角度       
  8. HSSFDataFormat df wb.createDataFormat();      
  9. style1.setDataFormat(df.getFormat("0.00%"));//设置单元格数据格式       
  10. cell.setCellFormula(string);//给单元格设公式       
  11. style.setRotation(short rotation);//单元格内容的旋转的角度   

 

 

 

15、插入图片

 

[c-sharp]   view plain copy print ?
  1. //先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray       
  2.       ByteArrayOutputStream byteArrayOut new ByteArrayOutputStream();      
  3.       BufferedImage bufferImg ImageIO.read(new File("ok.jpg"));      
  4.       ImageIO.write(bufferImg,"jpg",byteArrayOut);      
  5. //读进一个excel模版       
  6. FileInputStream fos new FileInputStream(filePathName+"/stencil.xlt");       
  7. fs new POIFSFileSystem(fos);      
  8. //创建一个工作薄       
  9. HSSFWorkbook wb new HSSFWorkbook(fs);      
  10. HSSFSheet sheet wb.getSheetAt(0);      
  11. HSSFPatriarch patriarch sheet.createDrawingPatriarch();      
  12. HSSFClientAnchor anchor new HSSFClientAnchor(0,0,1023,255,(short) 0,0,(short)10,10);           
  13. patriarch.createPicture(anchor wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));    

 

 

 

16、调整工作表位置

 

[c-sharp]   view plain copy print ?
  1. HSSFWorkbook wb new HSSFWorkbook();     
  2. HSSFSheet sheet wb.createSheet("format sheet");     
  3. HSSFPrintSetup ps sheet.getPrintSetup();     
  4. sheet.setAutobreaks(true);     
  5. ps.setFitHeight((short)1);     
  6. ps.setFitWidth((short)1);   
    

 

 

 

17、设置打印区域

 

[c-sharp]   view plain copy print ?
  1. HSSFSheet sheet wb.createSheet("Sheet1");     
  2. wb.setPrintArea(0, "$A$1:$C$2");    

 

 

 

18、标注脚注

 

[c-sharp]   view plain copy print ?
  1. HSSFSheet sheet wb.createSheet("format sheet");     
  2. HSSFFooter footer sheet.getFooter()     
  3. footer.setRight( "Page HSSFFooter.page() of HSSFFooter.numPages() );   

 

 

 

19、在工作单中清空行数据,调整行位置

 

[c-sharp]   view plain copy print ?
  1. HSSFWorkbook wb new HSSFWorkbook();     
  2. HSSFSheet sheet wb.createSheet("row sheet");     
  3. // Create various cells and rows for spreadsheet.      
  4. // Shift rows 11 on the spreadsheet to the top (rows 5)      
  5. sheet.shiftRows(5, 10, -5);    

 

 

 

20、选中指定的工作表

 

[c-sharp]   view plain copy print ?
  1. HSSFSheet sheet wb.createSheet("row sheet");     
  2. heet.setSelected(true);     

 

 

 

21、工作表的放大缩小

 

[c-sharp]   view plain copy print ?
  1. HSSFSheet sheet1 wb.createSheet("new sheet");     
  2. sheet1.setZoom(1,2);   // 50 percent magnification    

 

 

 

22、头注和脚注

 

[c-sharp]   view plain copy print ?
  1. HSSFSheet sheet wb.createSheet("new sheet");     
  2. HSSFHeader header sheet.getHeader();     
  3. header.setCenter("Center Header");     
  4. header.setLeft("Left Header");     
  5. header.setRight(HSSFHeader.font("Stencil-Normal", "Italic")     
  6. HSSFHeader.fontSize((short) 16) "Right w/ Stencil-Normal Italic font and size 16");  

 

 

 

23、自定义颜色

 

[c-sharp]   view plain copy print ?
  1. HSSFCellStyle style wb.createCellStyle();     
  2. style.setFillForegroundColor(HSSFColor.LIME.index);     
  3. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);     
  4. HSSFFont font wb.createFont();     
  5. font.setColor(HSSFColor.RED.index);     
  6. style.setFont(font);     
  7. cell.setCellStyle(style);     

 

 

 

24、填充和颜色设置

 

[c-sharp]   view plain copy print ?
  1. HSSFCellStyle style wb.createCellStyle();     
  2. style.setFillBackgroundColor(HSSFColor.AQUA.index);     
  3. style.setFillPattern(HSSFCellStyle.BIG_SPOTS);     
  4. HSSFCell cell row.createCell((short) 1);     
  5. cell.setCellValue("X");     
  6. style wb.createCellStyle();     
  7. style.setFillForegroundColor(HSSFColor.ORANGE.index);     
  8. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);     
  9. cell.setCellStyle(style);   

 

 

 

25、强行刷新单元格公式

 

[c-sharp]   view plain copy print ?
  1. HSSFFormulaEvaluator eval=new HSSFFormulaEvaluator((HSSFWorkbook) wb);    
  2. private static void updateFormula(Workbook wb,Sheet s,int row){     
  3.         Row r=s.getRow(row);     
  4.         Cell c=null;     
  5.         FormulaEcaluator eval=null;     
  6.         if(wb instanceof HSSFWorkbook)     
  7.             eval=new HSSFFormulaEvaluator((HSSFWorkbook) wb);     
  8.         else if(wb instanceof XSSFWorkbook)     
  9.             eval=new XSSFFormulaEvaluator((XSSFWorkbook) wb);     
  10.         for(int i=r.getFirstCellNum();i
  11.             c=r.getCell(i);     
  12.             if(c.getCellType()==Cell.CELL_TYPE_FORMULA)     
  13.                 eval.evaluateFormulaCell(c);     
  14.             
  15.        

 

 

 

说明:FormulaEvaluator提供了evaluateFormulaCell(Cell cell)方法,计算公式保存结果,但不改变公式。而evaluateInCell(Cell cell) 方法是计算公式,并将原公式替换为计算结果,也就是说该单元格的类型不在是Cell.CELL_TYPE_FORMULA而是Cell.CELL_TYPE_NUMBERIC。HSSFFormulaEvaluator提供了静态方法evaluateAllFormu

laCells(HSSFWorkbook wb) ,计算一个Excel文件的所有公式,用起来很方便。 

 

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------poi方法总结

-.设置不显示excel网格线 
  sheet.setDisplayGridlines(false);其中sheet是Sheet对象 
2.设置excel单元格中的内容换行 
  cellStyle.setWrapText(true);其中cellStyle是WorkBook创建的CellStyle对象,然后将cellStyle设置到要换行的Cell对象,最后在要换行的对象(一般为字符串)加入"/r/n"。如 
topTile.append("/r/n" +"cellContent"); 

3.单元格的合并 
  sheet.addMergedRegion(new CellRangeAddress(0, 4, 0, 2));本示例为合并4行2列 

4.设置页眉和页脚的页数 
    HSSFHeader header = sheet.getHeader(); 
    header.setCenter("Center Header"); 
    header.setLeft("Left Header"); 
    header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") + 
    HSSFHeader.fontSize((short) 16) + "Right w/ Stencil-Normal Italic font and size 16"); 

  HSSFFooter footer = (HSSFFooter )sheet.getFooter() 
  footer.setRight( "Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages() ); 

5.使得一个Sheet适合一页 
  sheet.setAutobreaks(true); 
6.设置放大属性(Zoom被明确为一个分数,例如下面的75%使用3作为分子,4作为分母) 
  sheet.setZoom(3,4);   

7.设置打印 
  HSSFPrintSetup print = (HSSFPrintSetup) sheet.getPrintSetup(); 
  print.setLandscape(true);//设置横向打印 
  print.setScale((short) 70);//设置打印缩放70% 
  print.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);//设置为A4纸张 
  print.setLeftToRight(true);//設置打印顺序先行后列,默认为先列行            
  print.setFitHeight((short) 10);设置缩放调整为10页高 
  print.setFitWidth((short) 10);设置缩放调整为宽高 

  sheet.setAutobreaks(false); 
  if (i != 0 && i % 30 == 0) 
      sheet.setRowBreak(i);//設置每30行分頁打印 

8.反复的行和列(设置打印标题) 
  HSSFWorkbook wb = new HSSFWorkbook(); 
  wb.setRepeatingRowsAndColumns(0, 0, 12, 1, 6);//设置1到12列,行1到6每一页重复打印 

9.调整单元格宽度 
  sheet.setAutobreaks(true); 
  sheet.setColumnWidth((short)i,colsWidth[i]); //设定单元格长度 
    sheet.autoSizeColumn((short) i);//自动根据长度调整单元格长度


----------------------------------------------------------------------------------------------------------------------------------------------------------

3表行的一些基本复制操作


public class POIUtils {
//	/**
//	 * 把一个excel中的cellstyletable复制到另一个excel,这里会报错,不能用这种方法,不明白呀?????
//	 * @param fromBook
//	 * @param toBook
//	 */
//	public static void copyBookCellStyle(HSSFWorkbook fromBook,HSSFWorkbook toBook){
//		for(short i=0;i<fromBook.getNumCellStyles();i++){
//			HSSFCellStyle fromStyle=fromBook.getCellStyleAt(i);
//			HSSFCellStyle toStyle=toBook.getCellStyleAt(i);
//			if(toStyle==null){
//				toStyle=toBook.createCellStyle();
//			}
//			copyCellStyle(fromStyle,toStyle);
//		}
//	}
	/**
	 * 复制一个单元格样式到目的单元格样式
	 * @param fromStyle
	 * @param toStyle
	 */
	public static void copyCellStyle(HSSFCellStyle fromStyle,
			HSSFCellStyle toStyle) {
		toStyle.setAlignment(fromStyle.getAlignment());
		//边框和边框颜色
		toStyle.setBorderBottom(fromStyle.getBorderBottom());
		toStyle.setBorderLeft(fromStyle.getBorderLeft());
		toStyle.setBorderRight(fromStyle.getBorderRight());
		toStyle.setBorderTop(fromStyle.getBorderTop());
		toStyle.setTopBorderColor(fromStyle.getTopBorderColor());
		toStyle.setBottomBorderColor(fromStyle.getBottomBorderColor());
		toStyle.setRightBorderColor(fromStyle.getRightBorderColor());
		toStyle.setLeftBorderColor(fromStyle.getLeftBorderColor());
		
		//背景和前景
		toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());
		toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());
		
		toStyle.setDataFormat(fromStyle.getDataFormat());
		toStyle.setFillPattern(fromStyle.getFillPattern());
//		toStyle.setFont(fromStyle.getFont(null));
		toStyle.setHidden(fromStyle.getHidden());
		toStyle.setIndention(fromStyle.getIndention());//首行缩进
		toStyle.setLocked(fromStyle.getLocked());
		toStyle.setRotation(fromStyle.getRotation());//旋转
		toStyle.setVerticalAlignment(fromStyle.getVerticalAlignment());
		toStyle.setWrapText(fromStyle.getWrapText());
		
	}
	/**
	 * Sheet复制
	 * @param fromSheet
	 * @param toSheet
	 * @param copyValueFlag
	 */
	public static void copySheet(HSSFWorkbook wb,HSSFSheet fromSheet, HSSFSheet toSheet,
			boolean copyValueFlag) {
		//合并区域处理
		mergerRegion(fromSheet, toSheet);
		for (Iterator rowIt = fromSheet.rowIterator(); rowIt.hasNext();) {
			HSSFRow tmpRow = (HSSFRow) rowIt.next();
			HSSFRow newRow = toSheet.createRow(tmpRow.getRowNum());
			//行复制
			copyRow(wb,tmpRow,newRow,copyValueFlag);
		}
	}
	/**
	 * 行复制功能
	 * @param fromRow
	 * @param toRow
	 */
	public static void copyRow(HSSFWorkbook wb,HSSFRow fromRow,HSSFRow toRow,boolean copyValueFlag){
		for (Iterator cellIt = fromRow.cellIterator(); cellIt.hasNext();) {
			HSSFCell tmpCell = (HSSFCell) cellIt.next();
			HSSFCell newCell = toRow.createCell(tmpCell.getCellNum());
			copyCell(wb,tmpCell, newCell, copyValueFlag);
		}
	}
	/**
	* 复制原有sheet的合并单元格到新创建的sheet
	* 
	* @param sheetCreat 新创建sheet
	* @param sheet      原有的sheet
	*/
	public static void mergerRegion(HSSFSheet fromSheet, HSSFSheet toSheet) {
	   int sheetMergerCount = fromSheet.getNumMergedRegions();
	   for (int i = 0; i < sheetMergerCount; i++) {
	    Region mergedRegionAt = fromSheet.getMergedRegionAt(i);
	    toSheet.addMergedRegion(mergedRegionAt);
	   }
	}
	/**
	 * 复制单元格
	 * 
	 * @param srcCell
	 * @param distCell
	 * @param copyValueFlag
	 *            true则连同cell的内容一起复制
	 */
	public static void copyCell(HSSFWorkbook wb,HSSFCell srcCell, HSSFCell distCell,
			boolean copyValueFlag) {
		HSSFCellStyle newstyle=wb.createCellStyle();
		copyCellStyle(srcCell.getCellStyle(), newstyle);
		distCell.setEncoding(srcCell.getEncoding());
		//样式
		distCell.setCellStyle(newstyle);
		//评论
		if (srcCell.getCellComment() != null) {
			distCell.setCellComment(srcCell.getCellComment());
		}
		// 不同数据类型处理
		int srcCellType = srcCell.getCellType();
		distCell.setCellType(srcCellType);
		if (copyValueFlag) {
			if (srcCellType == HSSFCell.CELL_TYPE_NUMERIC) {
				if (HSSFDateUtil.isCellDateFormatted(srcCell)) {
					distCell.setCellValue(srcCell.getDateCellValue());
				} else {
					distCell.setCellValue(srcCell.getNumericCellValue());
				}
			} else if (srcCellType == HSSFCell.CELL_TYPE_STRING) {
				distCell.setCellValue(srcCell.getRichStringCellValue());
			} else if (srcCellType == HSSFCell.CELL_TYPE_BLANK) {
				// nothing21
			} else if (srcCellType == HSSFCell.CELL_TYPE_BOOLEAN) {
				distCell.setCellValue(srcCell.getBooleanCellValue());
			} else if (srcCellType == HSSFCell.CELL_TYPE_ERROR) {
				distCell.setCellErrorValue(srcCell.getErrorCellValue());
			} else if (srcCellType == HSSFCell.CELL_TYPE_FORMULA) {
				distCell.setCellFormula(srcCell.getCellFormula());
			} else { // nothing29
			}
		}
	}
}


1 先来看一下HSSFBOOK的一些基本操作,样式

public ActionResult excelPrint() {  
    HSSFWorkbook workbook = new HSSFWorkbook();// 创建一个Excel文件  
    HSSFSheet sheet = workbook.createSheet();// 创建一个Excel的Sheet  
    sheet.createFreezePane(1, 3);// 冻结  
    // 设置列宽  
    sheet.setColumnWidth(0, 1000);  
    sheet.setColumnWidth(1, 3500);  
    sheet.setColumnWidth(2, 3500);  
    sheet.setColumnWidth(3, 6500);  
    sheet.setColumnWidth(4, 6500);  
    sheet.setColumnWidth(5, 6500);  
    sheet.setColumnWidth(6, 6500);  
    sheet.setColumnWidth(7, 2500);  
    // Sheet样式  
    HSSFCellStyle sheetStyle = workbook.createCellStyle();  
    // 背景色的设定  
    sheetStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);  
    // 前景色的设定  
    sheetStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);  
    // 填充模式  
    sheetStyle.setFillPattern(HSSFCellStyle.FINE_DOTS);  
    // 设置列的样式  
    for (int i = 0; i <= 14; i++) {  
      sheet.setDefaultColumnStyle((short) i, sheetStyle);  
    }  
    // 设置字体  
    HSSFFont headfont = workbook.createFont();  
    headfont.setFontName("黑体");  
    headfont.setFontHeightInPoints((short) 22);// 字体大小  
    headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗  
    // 另一个样式  
    HSSFCellStyle headstyle = workbook.createCellStyle();  
    headstyle.setFont(headfont);  
    headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
    headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中  
    headstyle.setLocked(true);  
    headstyle.setWrapText(true);// 自动换行  
    // 另一个字体样式  
    HSSFFont columnHeadFont = workbook.createFont();  
    columnHeadFont.setFontName("宋体");  
    columnHeadFont.setFontHeightInPoints((short) 10);  
    columnHeadFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
    // 列头的样式  
    HSSFCellStyle columnHeadStyle = workbook.createCellStyle();  
    columnHeadStyle.setFont(columnHeadFont);  
    columnHeadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
    columnHeadStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中  
    columnHeadStyle.setLocked(true);  
    columnHeadStyle.setWrapText(true);  
    columnHeadStyle.setLeftBorderColor(HSSFColor.BLACK.index);// 左边框的颜色  
    columnHeadStyle.setBorderLeft((short) 1);// 边框的大小  
    columnHeadStyle.setRightBorderColor(HSSFColor.BLACK.index);// 右边框的颜色  
    columnHeadStyle.setBorderRight((short) 1);// 边框的大小  
    columnHeadStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体  
    columnHeadStyle.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色  
    // 设置单元格的背景颜色(单元格的样式会覆盖列或行的样式)  
    columnHeadStyle.setFillForegroundColor(HSSFColor.WHITE.index);  
  
    HSSFFont font = workbook.createFont();  
    font.setFontName("宋体");  
    font.setFontHeightInPoints((short) 10);  
    // 普通单元格样式  
    HSSFCellStyle style = workbook.createCellStyle();  
    style.setFont(font);  
    style.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 左右居中  
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 上下居中  
    style.setWrapText(true);  
    style.setLeftBorderColor(HSSFColor.BLACK.index);  
    style.setBorderLeft((short) 1);  
    style.setRightBorderColor(HSSFColor.BLACK.index);  
    style.setBorderRight((short) 1);  
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体  
    style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色.  
    style.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色.  
    // 另一个样式  
    HSSFCellStyle centerstyle = workbook.createCellStyle();  
    centerstyle.setFont(font);  
    centerstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
    centerstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中  
    centerstyle.setWrapText(true);  
    centerstyle.setLeftBorderColor(HSSFColor.BLACK.index);  
    centerstyle.setBorderLeft((short) 1);  
    centerstyle.setRightBorderColor(HSSFColor.BLACK.index);  
    centerstyle.setBorderRight((short) 1);  
    centerstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体  
    centerstyle.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色.  
    centerstyle.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色.  
  
    try {  
      // 创建第一行  
      HSSFRow row0 = sheet.createRow(0);  
      // 设置行高  
      row0.setHeight((short) 900);  
      // 创建第一列  
      HSSFCell cell0 = row0.createCell(0);  
      cell0.setCellValue(new HSSFRichTextString("中非发展基金投资项目调度会工作落实情况对照表"));  
      cell0.setCellStyle(headstyle);  
      /** 
       * 合并单元格 
       *    第一个参数:第一个单元格的行数(从0开始) 
       *    第二个参数:第二个单元格的行数(从0开始) 
       *    第三个参数:第一个单元格的列数(从0开始) 
       *    第四个参数:第二个单元格的列数(从0开始) 
       */  
      CellRangeAddress range = new CellRangeAddress(0, 0, 0, 7);  
      sheet.addMergedRegion(range);  
      // 创建第二行  
      HSSFRow row1 = sheet.createRow(1);  
      HSSFCell cell1 = row1.createCell(0);  
      cell1.setCellValue(new HSSFRichTextString("本次会议时间:2009年8月31日       前次会议时间:2009年8月24日"));  
      cell1.setCellStyle(centerstyle);  
      // 合并单元格  
      range = new CellRangeAddress(1, 2, 0, 7);  
      sheet.addMergedRegion(range);  
      // 第三行  
      HSSFRow row2 = sheet.createRow(3);  
      row2.setHeight((short) 750);  
      HSSFCell cell = row2.createCell(0);  
      cell.setCellValue(new HSSFRichTextString("责任者"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(1);  
      cell.setCellValue(new HSSFRichTextString("成熟度排序"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(2);  
      cell.setCellValue(new HSSFRichTextString("事项"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(3);  
      cell.setCellValue(new HSSFRichTextString("前次会议要求\n/新项目的项目概要"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(4);  
      cell.setCellValue(new HSSFRichTextString("上周工作进展"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(5);  
      cell.setCellValue(new HSSFRichTextString("本周工作计划"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(6);  
      cell.setCellValue(new HSSFRichTextString("问题和建议"));  
      cell.setCellStyle(columnHeadStyle);  
      cell = row2.createCell(7);  
      cell.setCellValue(new HSSFRichTextString("备 注"));  
      cell.setCellStyle(columnHeadStyle);  
      // 访问数据库,得到数据集  
      List<DeitelVO> deitelVOList = getEntityManager().queryDeitelVOList();  
      int m = 4;  
      int k = 4;  
      for (int i = 0; i < deitelVOList.size(); i++) {  
        DeitelVO vo = deitelVOList.get(i);  
        String dname = vo.getDname();  
        List<Workinfo> workList = vo.getWorkInfoList();  
        HSSFRow row = sheet.createRow(m);  
        cell = row.createCell(0);  
        cell.setCellValue(new HSSFRichTextString(dname));  
        cell.setCellStyle(centerstyle);  
        // 合并单元格  
        range = new CellRangeAddress(m, m + workList.size() - 1, 0, 0);  
        sheet.addMergedRegion(range);  
        m = m + workList.size();  
  
        for (int j = 0; j < workList.size(); j++) {  
          Workinfo w = workList.get(j);  
          // 遍历数据集创建Excel的行  
          row = sheet.getRow(k + j);  
          if (null == row) {  
            row = sheet.createRow(k + j);  
          }  
          cell = row.createCell(1);  
          cell.setCellValue(w.getWnumber());  
          cell.setCellStyle(centerstyle);  
          cell = row.createCell(2);  
          cell.setCellValue(new HSSFRichTextString(w.getWitem()));  
          cell.setCellStyle(style);  
          cell = row.createCell(3);  
          cell.setCellValue(new HSSFRichTextString(w.getWmeting()));  
          cell.setCellStyle(style);  
          cell = row.createCell(4);  
          cell.setCellValue(new HSSFRichTextString(w.getWbweek()));  
          cell.setCellStyle(style);  
          cell = row.createCell(5);  
          cell.setCellValue(new HSSFRichTextString(w.getWtweek()));  
          cell.setCellStyle(style);  
          cell = row.createCell(6);  
          cell.setCellValue(new HSSFRichTextString(w.getWproblem()));  
          cell.setCellStyle(style);  
          cell = row.createCell(7);  
          cell.setCellValue(new HSSFRichTextString(w.getWremark()));  
          cell.setCellStyle(style);  
        }  
        k = k + workList.size();  
      }  
      // 列尾  
      int footRownumber = sheet.getLastRowNum();  
      HSSFRow footRow = sheet.createRow(footRownumber + 1);  
      HSSFCell footRowcell = footRow.createCell(0);  
      footRowcell.setCellValue(new HSSFRichTextString("                    审  定:XXX      审  核:XXX     汇  总:XX"));  
      footRowcell.setCellStyle(centerstyle);  
      range = new CellRangeAddress(footRownumber + 1, footRownumber + 1, 0, 7);  
      sheet.addMergedRegion(range);  
  
      HttpServletResponse response = getResponse();  
      HttpServletRequest request = getRequest();  
      String filename = "未命名.xls";//设置下载时客户端Excel的名称  
      // 请见:http://zmx.iteye.com/blog/622529  
      filename = Util.encodeFilename(filename, request);  
      response.setContentType("application/vnd.ms-excel");  
      response.setHeader("Content-disposition", "attachment;filename=" + filename);  
      OutputStream ouputStream = response.getOutputStream();  
      workbook.write(ouputStream);  
      ouputStream.flush();  
      ouputStream.close();  
  
    } catch (Exception e) {  
      e.printStackTrace();  
    }  
    return null;  
  }  


-----------------------------------------------------------------------------

2 POI的一些方法

一、 POI简介

            Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

二、 HSSF概况

            HSSF 是Horrible SpreadSheet Format的缩写,通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。

三、 POI EXCEL文档结构类

            HSSFWorkbook excel文档对象

            HSSFSheet excel的sheet HSSFRow excel的行

            HSSFCell excel的单元格 HSSFFont excel字体

            HSSFName 名称 HSSFDataFormat 日期格式

            HSSFHeader sheet头

            HSSFFooter sheet尾

            HSSFCellStyle cell样式

            HSSFDateUtil 日期

            HSSFPrintSetup 打印

            HSSFErrorConstants 错误信息表

四、 EXCEL常用操作方法

  1、 得到Excel常用对象           
  1. POIFSFileSystem fs=newPOIFSFileSystem(new FileInputStream("d:/test.xls"));   
  2. //得到Excel工作簿对象    
  3. HSSFWorkbook wb new HSSFWorkbook(fs);  
  4. //得到Excel工作表对象    
  5. HSSFSheet sheet wb.getSheetAt(0);   
  6. //得到Excel工作表的行    
  7. HSSFRow row sheet.getRow(i);  
  8. //得到Excel工作表指定行的单元格    
  9. HSSFCell cell row.getCell((short) j);  
  10. cellStyle cell.getCellStyle();//得到单元格样式  
 2、建立Excel常用对象
  1. HSSFWorkbook wb new HSSFWorkbook();//创建Excel工作簿对象   
  2. HSSFSheet sheet wb.createSheet("new sheet");//创建Excel工作表对象     
  3. HSSFRow row sheet.createRow((short)0); //创建Excel工作表的行   
  4. cellStyle wb.createCellStyle();//创建单元格样式   
  5. row.createCell((short)0).setCellStyle(cellStyle); //创建Excel工作表指定行的单元格   
  6. row.createCell((short)0).setCellValue(1); //设置Excel工作表的值  
3、设置sheet名称和单元格内容
  1. wb.setSheetName(1, "第一张工作表",HSSFCell.ENCODING_UTF_16);          
  2. cell.setEncoding((short) 1);      
  3. cell.setCellValue("单元格内容");  
4、取得sheet的数目 
  1. wb.getNumberOfSheets()   
5、  根据index取得sheet对象
  1. HSSFSheet sheet wb.getSheetAt(0);  
6、取得有效的行数
  1. int rowcount sheet.getLastRowNum();  
7、取得一行的有效单元格个数
  1. row.getLastCellNum();    

8、单元格值类型读写

 

[c-sharp]   view plain copy print ?
  1. cell.setCellType(HSSFCell.CELL_TYPE_STRING); //设置单元格为STRING类型   
  2. cell.getNumericCellValue();//读取为数值类型的单元格内容  

 

 

 

9、设置列宽、行高

 

[c-sharp]   view plain copy print ?
  1. sheet.setColumnWidth((short)column,(short)width);      
  2. row.setHeight((short)height);    

 

 

 

10、添加区域,合并单元格

 

[c-sharp]   view plain copy print ?
  1. Region region new Region((short)rowFrom,(short)columnFrom,(short)rowTo  
  2. ,(short)columnTo);//合并从第rowFrom行columnFrom列   
  3. sheet.addMergedRegion(region);// 到rowTo行columnTo的区域      
  4. //得到所有区域       
  5. sheet.getNumMergedRegions()   

 

 

 

11、保存Excel文件

 

[c-sharp]   view plain copy print ?
  1. FileOutputStream fileOut new FileOutputStream(path);   
  2. wb.write(fileOut);   

 

 

 

12、根据单元格不同属性返回字符串数值

 

[c-sharp]   view plain copy print ?
  1. public String getCellStringValue(HSSFCell cell)      
  2.         String cellValue "";      
  3.         switch (cell.getCellType())      
  4.         case HSSFCell.CELL_TYPE_STRING://字符串类型   
  5.             cellValue cell.getStringCellValue();      
  6.             if(cellValue.trim().equals("")||cellValue.trim().length()<=0)      
  7.                 cellValue=" ";      
  8.             break;      
  9.         case HSSFCell.CELL_TYPE_NUMERIC: //数值类型   
  10.             cellValue String.valueOf(cell.getNumericCellValue());      
  11.             break;      
  12.         case HSSFCell.CELL_TYPE_FORMULA: //公式   
  13.             cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);      
  14.             cellValue String.valueOf(cell.getNumericCellValue());      
  15.             break;      
  16.         case HSSFCell.CELL_TYPE_BLANK:      
  17.             cellValue=" ";      
  18.             break;      
  19.         case HSSFCell.CELL_TYPE_BOOLEAN:      
  20.             break;      
  21.         case HSSFCell.CELL_TYPE_ERROR:      
  22.             break;      
  23.         default:      
  24.             break;      
  25.              
  26.         return cellValue;      
  27.         

 

 

 

13、常用单元格边框格式

 

[c-sharp]   view plain copy print ?
  1. HSSFCellStyle style wb.createCellStyle();      
  2. style.setBorderBottom(HSSFCellStyle.BORDER_DOTTED);//下边框        
  3. style.setBorderLeft(HSSFCellStyle.BORDER_DOTTED);//左边框        
  4. style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框        
  5. style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框    

 

 

 

14、设置字体和内容位置

 

[c-sharp]   view plain copy print ?
  1. HSSFFont  wb.createFont();      
  2. f.setFontHeightInPoints((short) 11);//字号       
  3. f.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//加粗       
  4. style.setFont(f);      
  5. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中       
  6. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中       
  7. style.setRotation(short rotation);//单元格内容的旋转的角度       
  8. HSSFDataFormat df wb.createDataFormat();      
  9. style1.setDataFormat(df.getFormat("0.00%"));//设置单元格数据格式       
  10. cell.setCellFormula(string);//给单元格设公式       
  11. style.setRotation(short rotation);//单元格内容的旋转的角度   

 

 

 

15、插入图片

 

[c-sharp]   view plain copy print ?
  1. //先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray       
  2.       ByteArrayOutputStream byteArrayOut new ByteArrayOutputStream();      
  3.       BufferedImage bufferImg ImageIO.read(new File("ok.jpg"));      
  4.       ImageIO.write(bufferImg,"jpg",byteArrayOut);      
  5. //读进一个excel模版       
  6. FileInputStream fos new FileInputStream(filePathName+"/stencil.xlt");       
  7. fs new POIFSFileSystem(fos);      
  8. //创建一个工作薄       
  9. HSSFWorkbook wb new HSSFWorkbook(fs);      
  10. HSSFSheet sheet wb.getSheetAt(0);      
  11. HSSFPatriarch patriarch sheet.createDrawingPatriarch();      
  12. HSSFClientAnchor anchor new HSSFClientAnchor(0,0,1023,255,(short) 0,0,(short)10,10);           
  13. patriarch.createPicture(anchor wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));    

 

 

 

16、调整工作表位置

 

[c-sharp]   view plain copy print ?
  1. HSSFWorkbook wb new HSSFWorkbook();     
  2. HSSFSheet sheet wb.createSheet("format sheet");     
  3. HSSFPrintSetup ps sheet.getPrintSetup();     
  4. sheet.setAutobreaks(true);     
  5. ps.setFitHeight((short)1);     
  6. ps.setFitWidth((short)1);   
    

 

 

 

17、设置打印区域

 

[c-sharp]   view plain copy print ?
  1. HSSFSheet sheet wb.createSheet("Sheet1");     
  2. wb.setPrintArea(0, "$A$1:$C$2");    

 

 

 

18、标注脚注

 

[c-sharp]   view plain copy print ?
  1. HSSFSheet sheet wb.createSheet("format sheet");     
  2. HSSFFooter footer sheet.getFooter()     
  3. footer.setRight( "Page HSSFFooter.page() of HSSFFooter.numPages() );   

 

 

 

19、在工作单中清空行数据,调整行位置

 

[c-sharp]   view plain copy print ?
  1. HSSFWorkbook wb new HSSFWorkbook();     
  2. HSSFSheet sheet wb.createSheet("row sheet");     
  3. // Create various cells and rows for spreadsheet.      
  4. // Shift rows 11 on the spreadsheet to the top (rows 5)      
  5. sheet.shiftRows(5, 10, -5);    

 

 

 

20、选中指定的工作表

 

[c-sharp]   view plain copy print ?
  1. HSSFSheet sheet wb.createSheet("row sheet");     
  2. heet.setSelected(true);     

 

 

 

21、工作表的放大缩小

 

[c-sharp]   view plain copy print ?
  1. HSSFSheet sheet1 wb.createSheet("new sheet");     
  2. sheet1.setZoom(1,2);   // 50 percent magnification    

 

 

 

22、头注和脚注

 

[c-sharp]   view plain copy print ?
  1. HSSFSheet sheet wb.createSheet("new sheet");     
  2. HSSFHeader header sheet.getHeader();     
  3. header.setCenter("Center Header");     
  4. header.setLeft("Left Header");     
  5. header.setRight(HSSFHeader.font("Stencil-Normal", "Italic")     
  6. HSSFHeader.fontSize((short) 16) "Right w/ Stencil-Normal Italic font and size 16");  

 

 

 

23、自定义颜色

 

[c-sharp]   view plain copy print ?
  1. HSSFCellStyle style wb.createCellStyle();     
  2. style.setFillForegroundColor(HSSFColor.LIME.index);     
  3. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);     
  4. HSSFFont font wb.createFont();     
  5. font.setColor(HSSFColor.RED.index);     
  6. style.setFont(font);     
  7. cell.setCellStyle(style);     

 

 

 

24、填充和颜色设置

 

[c-sharp]   view plain copy print ?
  1. HSSFCellStyle style wb.createCellStyle();     
  2. style.setFillBackgroundColor(HSSFColor.AQUA.index);     
  3. style.setFillPattern(HSSFCellStyle.BIG_SPOTS);     
  4. HSSFCell cell row.createCell((short) 1);     
  5. cell.setCellValue("X");     
  6. style wb.createCellStyle();     
  7. style.setFillForegroundColor(HSSFColor.ORANGE.index);     
  8. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);     
  9. cell.setCellStyle(style);   

 

 

 

25、强行刷新单元格公式

 

[c-sharp]   view plain copy print ?
  1. HSSFFormulaEvaluator eval=new HSSFFormulaEvaluator((HSSFWorkbook) wb);    
  2. private static void updateFormula(Workbook wb,Sheet s,int row){     
  3.         Row r=s.getRow(row);     
  4.         Cell c=null;     
  5.         FormulaEcaluator eval=null;     
  6.         if(wb instanceof HSSFWorkbook)     
  7.             eval=new HSSFFormulaEvaluator((HSSFWorkbook) wb);     
  8.         else if(wb instanceof XSSFWorkbook)     
  9.             eval=new XSSFFormulaEvaluator((XSSFWorkbook) wb);     
  10.         for(int i=r.getFirstCellNum();i
  11.             c=r.getCell(i);     
  12.             if(c.getCellType()==Cell.CELL_TYPE_FORMULA)     
  13.                 eval.evaluateFormulaCell(c);     
  14.             
  15.        

 

 

 

说明:FormulaEvaluator提供了evaluateFormulaCell(Cell cell)方法,计算公式保存结果,但不改变公式。而evaluateInCell(Cell cell) 方法是计算公式,并将原公式替换为计算结果,也就是说该单元格的类型不在是Cell.CELL_TYPE_FORMULA而是Cell.CELL_TYPE_NUMBERIC。HSSFFormulaEvaluator提供了静态方法evaluateAllFormu

laCells(HSSFWorkbook wb) ,计算一个Excel文件的所有公式,用起来很方便。 

 

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------poi方法总结

-.设置不显示excel网格线 
  sheet.setDisplayGridlines(false);其中sheet是Sheet对象 
2.设置excel单元格中的内容换行 
  cellStyle.setWrapText(true);其中cellStyle是WorkBook创建的CellStyle对象,然后将cellStyle设置到要换行的Cell对象,最后在要换行的对象(一般为字符串)加入"/r/n"。如 
topTile.append("/r/n" +"cellContent"); 

3.单元格的合并 
  sheet.addMergedRegion(new CellRangeAddress(0, 4, 0, 2));本示例为合并4行2列 

4.设置页眉和页脚的页数 
    HSSFHeader header = sheet.getHeader(); 
    header.setCenter("Center Header"); 
    header.setLeft("Left Header"); 
    header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") + 
    HSSFHeader.fontSize((short) 16) + "Right w/ Stencil-Normal Italic font and size 16"); 

  HSSFFooter footer = (HSSFFooter )sheet.getFooter() 
  footer.setRight( "Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages() ); 

5.使得一个Sheet适合一页 
  sheet.setAutobreaks(true); 
6.设置放大属性(Zoom被明确为一个分数,例如下面的75%使用3作为分子,4作为分母) 
  sheet.setZoom(3,4);   

7.设置打印 
  HSSFPrintSetup print = (HSSFPrintSetup) sheet.getPrintSetup(); 
  print.setLandscape(true);//设置横向打印 
  print.setScale((short) 70);//设置打印缩放70% 
  print.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);//设置为A4纸张 
  print.setLeftToRight(true);//設置打印顺序先行后列,默认为先列行            
  print.setFitHeight((short) 10);设置缩放调整为10页高 
  print.setFitWidth((short) 10);设置缩放调整为宽高 

  sheet.setAutobreaks(false); 
  if (i != 0 && i % 30 == 0) 
      sheet.setRowBreak(i);//設置每30行分頁打印 

8.反复的行和列(设置打印标题) 
  HSSFWorkbook wb = new HSSFWorkbook(); 
  wb.setRepeatingRowsAndColumns(0, 0, 12, 1, 6);//设置1到12列,行1到6每一页重复打印 

9.调整单元格宽度 
  sheet.setAutobreaks(true); 
  sheet.setColumnWidth((short)i,colsWidth[i]); //设定单元格长度 
    sheet.autoSizeColumn((short) i);//自动根据长度调整单元格长度


----------------------------------------------------------------------------------------------------------------------------------------------------------

3表行的一些基本复制操作


public class POIUtils {
//	/**
//	 * 把一个excel中的cellstyletable复制到另一个excel,这里会报错,不能用这种方法,不明白呀?????
//	 * @param fromBook
//	 * @param toBook
//	 */
//	public static void copyBookCellStyle(HSSFWorkbook fromBook,HSSFWorkbook toBook){
//		for(short i=0;i<fromBook.getNumCellStyles();i++){
//			HSSFCellStyle fromStyle=fromBook.getCellStyleAt(i);
//			HSSFCellStyle toStyle=toBook.getCellStyleAt(i);
//			if(toStyle==null){
//				toStyle=toBook.createCellStyle();
//			}
//			copyCellStyle(fromStyle,toStyle);
//		}
//	}
	/**
	 * 复制一个单元格样式到目的单元格样式
	 * @param fromStyle
	 * @param toStyle
	 */
	public static void copyCellStyle(HSSFCellStyle fromStyle,
			HSSFCellStyle toStyle) {
		toStyle.setAlignment(fromStyle.getAlignment());
		//边框和边框颜色
		toStyle.setBorderBottom(fromStyle.getBorderBottom());
		toStyle.setBorderLeft(fromStyle.getBorderLeft());
		toStyle.setBorderRight(fromStyle.getBorderRight());
		toStyle.setBorderTop(fromStyle.getBorderTop());
		toStyle.setTopBorderColor(fromStyle.getTopBorderColor());
		toStyle.setBottomBorderColor(fromStyle.getBottomBorderColor());
		toStyle.setRightBorderColor(fromStyle.getRightBorderColor());
		toStyle.setLeftBorderColor(fromStyle.getLeftBorderColor());
		
		//背景和前景
		toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());
		toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());
		
		toStyle.setDataFormat(fromStyle.getDataFormat());
		toStyle.setFillPattern(fromStyle.getFillPattern());
//		toStyle.setFont(fromStyle.getFont(null));
		toStyle.setHidden(fromStyle.getHidden());
		toStyle.setIndention(fromStyle.getIndention());//首行缩进
		toStyle.setLocked(fromStyle.getLocked());
		toStyle.setRotation(fromStyle.getRotation());//旋转
		toStyle.setVerticalAlignment(fromStyle.getVerticalAlignment());
		toStyle.setWrapText(fromStyle.getWrapText());
		
	}
	/**
	 * Sheet复制
	 * @param fromSheet
	 * @param toSheet
	 * @param copyValueFlag
	 */
	public static void copySheet(HSSFWorkbook wb,HSSFSheet fromSheet, HSSFSheet toSheet,
			boolean copyValueFlag) {
		//合并区域处理
		mergerRegion(fromSheet, toSheet);
		for (Iterator rowIt = fromSheet.rowIterator(); rowIt.hasNext();) {
			HSSFRow tmpRow = (HSSFRow) rowIt.next();
			HSSFRow newRow = toSheet.createRow(tmpRow.getRowNum());
			//行复制
			copyRow(wb,tmpRow,newRow,copyValueFlag);
		}
	}
	/**
	 * 行复制功能
	 * @param fromRow
	 * @param toRow
	 */
	public static void copyRow(HSSFWorkbook wb,HSSFRow fromRow,HSSFRow toRow,boolean copyValueFlag){
		for (Iterator cellIt = fromRow.cellIterator(); cellIt.hasNext();) {
			HSSFCell tmpCell = (HSSFCell) cellIt.next();
			HSSFCell newCell = toRow.createCell(tmpCell.getCellNum());
			copyCell(wb,tmpCell, newCell, copyValueFlag);
		}
	}
	/**
	* 复制原有sheet的合并单元格到新创建的sheet
	* 
	* @param sheetCreat 新创建sheet
	* @param sheet      原有的sheet
	*/
	public static void mergerRegion(HSSFSheet fromSheet, HSSFSheet toSheet) {
	   int sheetMergerCount = fromSheet.getNumMergedRegions();
	   for (int i = 0; i < sheetMergerCount; i++) {
	    Region mergedRegionAt = fromSheet.getMergedRegionAt(i);
	    toSheet.addMergedRegion(mergedRegionAt);
	   }
	}
	/**
	 * 复制单元格
	 * 
	 * @param srcCell
	 * @param distCell
	 * @param copyValueFlag
	 *            true则连同cell的内容一起复制
	 */
	public static void copyCell(HSSFWorkbook wb,HSSFCell srcCell, HSSFCell distCell,
			boolean copyValueFlag) {
		HSSFCellStyle newstyle=wb.createCellStyle();
		copyCellStyle(srcCell.getCellStyle(), newstyle);
		distCell.setEncoding(srcCell.getEncoding());
		//样式
		distCell.setCellStyle(newstyle);
		//评论
		if (srcCell.getCellComment() != null) {
			distCell.setCellComment(srcCell.getCellComment());
		}
		// 不同数据类型处理
		int srcCellType = srcCell.getCellType();
		distCell.setCellType(srcCellType);
		if (copyValueFlag) {
			if (srcCellType == HSSFCell.CELL_TYPE_NUMERIC) {
				if (HSSFDateUtil.isCellDateFormatted(srcCell)) {
					distCell.setCellValue(srcCell.getDateCellValue());
				} else {
					distCell.setCellValue(srcCell.getNumericCellValue());
				}
			} else if (srcCellType == HSSFCell.CELL_TYPE_STRING) {
				distCell.setCellValue(srcCell.getRichStringCellValue());
			} else if (srcCellType == HSSFCell.CELL_TYPE_BLANK) {
				// nothing21
			} else if (srcCellType == HSSFCell.CELL_TYPE_BOOLEAN) {
				distCell.setCellValue(srcCell.getBooleanCellValue());
			} else if (srcCellType == HSSFCell.CELL_TYPE_ERROR) {
				distCell.setCellErrorValue(srcCell.getErrorCellValue());
			} else if (srcCellType == HSSFCell.CELL_TYPE_FORMULA) {
				distCell.setCellFormula(srcCell.getCellFormula());
			} else { // nothing29
			}
		}
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值