poi操作Excel

java读取excel文件的顺序是: 
Excel文件->工作表->行->单元格 对应到POI中,为:workbook->sheet->row->cell 
注意: 
注意:   
   1.sheet, 以0开始,以workbook.getNumberOfSheets()-1结束 
   2.row, 以0开始(getFirstRowNum),以getLastRowNum结束 
   3.cell, 以0开始(getFirstCellNum),以getLastCellNum结束, 
     结束的数目不知什么原因与显示的长度不同,可能会偏长 

  1. //import org.apache.poi.ss.usermodel.contrib.CellUtil;  
  2. //import org.apache.poi.ss.usermodel.contrib.RegionUtil;  
  3. 这两个类已更换到 这两个类移动是3.7开始变的  
  4. //import org.apache.poi.ss.util.CellUtil;  
  5. //import org.apache.poi.ss.util.RegionUtil;  
  1. package com.svse.test;  
  2.   
  3.   
  4. import java.awt.Color;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.util.Calendar;  
  11. import java.util.Date;  
  12.   
  13.   
  14. import org.apache.poi.hssf.usermodel.HSSFCell;  
  15. import org.apache.poi.hssf.usermodel.HSSFClientAnchor;  
  16. import org.apache.poi.hssf.usermodel.HSSFFooter;  
  17. import org.apache.poi.hssf.usermodel.HSSFPatriarch;  
  18. import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
  19. import org.apache.poi.hssf.usermodel.HSSFShape;  
  20. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  21. import org.apache.poi.hssf.usermodel.HSSFSimpleShape;  
  22. import org.apache.poi.hssf.usermodel.HSSFTextbox;  
  23. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  24. import org.apache.poi.hssf.util.HSSFColor;  
  25. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;  
  26. import org.apache.poi.ss.usermodel.Cell;  
  27. import org.apache.poi.ss.usermodel.CellStyle;  
  28. import org.apache.poi.ss.usermodel.ClientAnchor;  
  29. import org.apache.poi.ss.usermodel.CreationHelper;  
  30. import org.apache.poi.ss.usermodel.DataFormat;  
  31. import org.apache.poi.ss.usermodel.DateUtil;  
  32. import org.apache.poi.ss.usermodel.Drawing;  
  33. import org.apache.poi.ss.usermodel.Font;  
  34. import org.apache.poi.ss.usermodel.IndexedColors;  
  35. import org.apache.poi.ss.usermodel.Picture;  
  36. import org.apache.poi.ss.usermodel.PrintSetup;  
  37. import org.apache.poi.ss.usermodel.RichTextString;  
  38. import org.apache.poi.ss.usermodel.Row;  
  39. import org.apache.poi.ss.usermodel.Sheet;  
  40. import org.apache.poi.ss.usermodel.Workbook;  
  41. import org.apache.poi.ss.usermodel.WorkbookFactory;  
  42. //import org.apache.poi.ss.usermodel.contrib.CellUtil;  
  43. //import org.apache.poi.ss.usermodel.contrib.RegionUtil;  
  44. import org.apache.poi.ss.util.CellRangeAddress;  
  45. import org.apache.poi.ss.util.CellReference;  
  46. import org.apache.poi.ss.util.CellUtil;  
  47. import org.apache.poi.ss.util.RegionUtil;  
  48. import org.apache.poi.util.IOUtils;  
  49. import org.apache.poi.xssf.usermodel.XSSFCellStyle;  
  50. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  51. import org.junit.BeforeClass;  
  52. import org.junit.Test;  
  53.   
  54.   
  55. /** 
  56.  * @author WESTDREAM 
  57.  * @since 2010-8-7 下午10:34:03 
  58.  */  
  59. public class POIExcelTest {  
  60.   
  61.   
  62.     /** 
  63.      * @throws java.lang.Exception 
  64.      */  
  65.     public static final String XLS_WORKBOOK_LOCATION = "D:/workbook.xls";  
  66.     public static final String XLS_OR_XLSX_DIR = "D:/";  
  67.     public static final String XLSX_WORKBOOK_LOCATION = "D:/workbook.xlsx";  
  68.     public static final String IMAGE_LOCATION = "book.jpg";  
  69.   
  70.   
  71.     @BeforeClass  
  72.     public static void setUpBeforeClass() throws Exception {  
  73.   
  74.   
  75.     }  
  76.   
  77.   
  78.     @Test  
  79.     public void testWriteExcel() {  
  80.         // ## 重复利用 的对象 ##//  
  81.         Workbook wb = null;  
  82.         FileOutputStream fileOut = null;  
  83.         CellStyle cellStyle = null;  
  84.         Cell cell = null;  
  85.         Font font = null;  
  86.   
  87.   
  88.         /** 
  89.          * EXCEL早期版本 
  90.          */  
  91.         try {  
  92.             // ## 创建早期EXCEL的Workbook ##//  
  93.             wb = new HSSFWorkbook();  
  94.             // ## 获取HSSF和XSSF的辅助类 ##//  
  95.             CreationHelper createHelper = wb.getCreationHelper();  
  96.             // ## 创建一个名为“New Sheet”的Sheet ##//  
  97.             Sheet sheet = wb.createSheet("New Sheet");  
  98.   
  99.   
  100.             /** 第一行 --- CELL创建,数据填充及日期格式 **/  
  101.             Row row1 = sheet.createRow(0);  
  102.             // Cell cell = row.createCell(0);  
  103.             // cell.setCellValue(1);  
  104.   
  105.   
  106.             // ## 在相应的位置填充数据 ##//  
  107.             row1.createCell(0).setCellValue(1);  
  108.             row1.createCell(1).setCellValue(1.2);  
  109.             row1.createCell(2).setCellValue(  
  110.                     createHelper.createRichTextString("CreationHelper---字符串"));  
  111.             row1.createCell(3).setCellValue(true);  
  112.   
  113.   
  114.             // ## 填充日期类型的数据---未设置Cell Style ##//  
  115.             row1.createCell(4).setCellValue(new Date());  
  116.             // ## 填充日期类型的数据---已设置Cell Style ##//  
  117.             cellStyle = wb.createCellStyle();  
  118.             cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(  
  119.                     "yyyy年MM月dd日 hh:mm:ss"));  
  120.             // cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("mm/dd/yyyy h:mm"));  
  121.             cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(  
  122.                     "yyyy-MM-dd hh:mm:ss"));  
  123.             cell = row1.createCell(5);  
  124.             cell.setCellValue(new Date());  
  125.             cell.setCellStyle(cellStyle);  
  126.             // ## 另一种创建日期的方法 ##//  
  127.             /* 
  128.              * cell = row1.createCell(6); 
  129.              * cell.setCellValue(Calendar.getInstance()); 
  130.              * cell.setCellStyle(cellStyle); 
  131.              */  
  132.   
  133.   
  134.             /** 第二行 --- 数据类型 **/  
  135.             Row row2 = sheet.createRow(1);  
  136.             row2.createCell(0).setCellValue(1.1);  
  137.             row2.createCell(1).setCellValue(new Date());  
  138.             row2.createCell(2).setCellValue(Calendar.getInstance());  
  139.             row2.createCell(3).setCellValue("字符串");  
  140.             row2.createCell(4).setCellValue(true);  
  141.             // ## 错误的CELL数据格式 ##//  
  142.             row2.createCell(5).setCellType(HSSFCell.CELL_TYPE_ERROR);  
  143.   
  144.   
  145.             /** 第三行 --- CELL的各种对齐方式 **/  
  146.             Row row3 = sheet.createRow(2);  
  147.             row3.setHeightInPoints(30);  
  148.             // ## 水平居中,底端对齐 ##//  
  149.             createCell(wb, row3, (short0, XSSFCellStyle.ALIGN_CENTER,  
  150.                     XSSFCellStyle.VERTICAL_BOTTOM);  
  151.             // ## 水平居中,垂直居中 ##//  
  152.             createCell(wb, row3, (short1,  
  153.                     XSSFCellStyle.ALIGN_CENTER_SELECTION,  
  154.                     XSSFCellStyle.VERTICAL_BOTTOM);  
  155.             // ## 填充 ,垂直居中 ##//  
  156.             createCell(wb, row3, (short2, XSSFCellStyle.ALIGN_FILL,  
  157.                     XSSFCellStyle.VERTICAL_CENTER);  
  158.             // ## 左对齐,垂直居中 ##//  
  159.             createCell(wb, row3, (short3, XSSFCellStyle.ALIGN_GENERAL,  
  160.                     XSSFCellStyle.VERTICAL_CENTER);  
  161.             // ## 左对齐,顶端对齐 ##//  
  162.             createCell(wb, row3, (short4, XSSFCellStyle.ALIGN_JUSTIFY,  
  163.                     XSSFCellStyle.VERTICAL_JUSTIFY);  
  164.             // ## 左对齐,顶端对齐 ##//  
  165.             createCell(wb, row3, (short5, XSSFCellStyle.ALIGN_LEFT,  
  166.                     XSSFCellStyle.VERTICAL_TOP);  
  167.             // ## 右对齐,顶端对齐 ##//  
  168.             createCell(wb, row3, (short6, XSSFCellStyle.ALIGN_RIGHT,  
  169.                     XSSFCellStyle.VERTICAL_TOP);  
  170.   
  171.   
  172.             /** 第四行 --- CELL边框 **/  
  173.             Row row4 = sheet.createRow(3);  
  174.             cell = row4.createCell(1);  
  175.             cell.setCellValue(4);  
  176.             cellStyle = wb.createCellStyle();  
  177.             // ## 设置底部边框为THIN ##//  
  178.             cellStyle.setBorderBottom(CellStyle.BORDER_THIN);  
  179.             // ## 设置底部边框颜色为黑色 ##//  
  180.             cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());  
  181.             // ## 设置左边边框为THIN ##//  
  182.             cellStyle.setBorderLeft(CellStyle.BORDER_THIN);  
  183.             // ## 设置左边边框颜色为红色 ##//  
  184.             cellStyle.setLeftBorderColor(IndexedColors.RED.getIndex());  
  185.             // ## 设置右边边框为THIN ##//  
  186.             cellStyle.setBorderRight(CellStyle.BORDER_THIN);  
  187.             // ## 设置右边边框颜色为蓝色 ##//  
  188.             cellStyle.setRightBorderColor(IndexedColors.BLUE.getIndex());  
  189.             // ## 设置顶部边框为MEDIUM DASHED ##//  
  190.             cellStyle.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);  
  191.             // ## 设置顶部边框颜色为黑色 ##//  
  192.             cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());  
  193.             cell.setCellStyle(cellStyle);  
  194.   
  195.   
  196.             /** 第五行 --- 填充与颜色 **/  
  197.             Row row5 = sheet.createRow((short4);  
  198.             // ## Aqua背景 ##//  
  199.             cellStyle = wb.createCellStyle();  
  200.             cellStyle.setFillBackgroundColor(IndexedColors.AQUA.getIndex());  
  201.             // ## 设置填充模式为BIG SPOTS ##//  
  202.             cellStyle.setFillPattern(CellStyle.BIG_SPOTS);  
  203.             cell = row5.createCell((short1);  
  204.             cell.setCellValue("Aqua背景");  
  205.             cell.setCellStyle(cellStyle);  
  206.   
  207.   
  208.             // ## 橙色前景色(相对 于CELL背景) ##//  
  209.             cellStyle = wb.createCellStyle();  
  210.             cellStyle.setFillForegroundColor(IndexedColors.ORANGE.getIndex());  
  211.             // ## 设置填充模式为SOLID FOREGROUND ##//  
  212.             cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  213.             cell = row5.createCell((short2);  
  214.             cell.setCellValue("橙色前景色");  
  215.             cell.setCellStyle(cellStyle);  
  216.   
  217.   
  218.             /** 第六行 --- 合并单元格 **/  
  219.             Row row6 = sheet.createRow((short5);  
  220.             cell = row6.createCell((short4);  
  221.             cell.setCellValue("合并单元格测试");  
  222.             // ## Wrong:EXCEL 2007中打开workbook.xls文件看不到"合并单元格测试",但单元格已经合并了 ##//  
  223.             /* 
  224.              * sheet.addMergedRegion(new CellRangeAddress( 3, //first row 
  225.              * (0-based) 5, //last row (0-based) 4, //first column (0-based) 6 
  226.              * //last column (0-based) )); 
  227.              */  
  228.             // ## 正确合并单元格 注意:与上不同的是first row=last row ##//  
  229.             sheet.addMergedRegion(new CellRangeAddress(5// first row (0-based)  
  230.                     5// last row (0-based)  
  231.                     4// first column (0-based)  
  232.                     6// last column (0-based)  
  233.                     ));  
  234.   
  235.   
  236.             /** 第七行 --- 字体 **/  
  237.             Row row7 = sheet.createRow(6);  
  238.             // ## 创建字体 ##//  
  239.             // 注意:POI限制一个Workbook创建的Font对象最多为32767,所以不要为每个CELL创建一个字体,建议重用字体  
  240.             font = wb.createFont();  
  241.             // ## 设置字体大小为24 ##//  
  242.             font.setFontHeightInPoints((short24);  
  243.             // ## 设置字体样式为华文隶书 ##//  
  244.             font.setFontName("华文隶书");  
  245.             // ## 斜体 ##//  
  246.             font.setItalic(true);  
  247.             // ## 添加删除线 ##//  
  248.             font.setStrikeout(true);  
  249.             // ## 将字体添加到样式中 ##//  
  250.             cellStyle = wb.createCellStyle();  
  251.             cellStyle.setFont(font);  
  252.             cell = row7.createCell(1);  
  253.             cell.setCellValue("字体测试");  
  254.             cell.setCellStyle(cellStyle);  
  255.   
  256.   
  257.             /** 第八行 --- 自定义颜色 **/  
  258.             Row row8 = sheet.createRow(7);  
  259.             cell = row8.createCell(0);  
  260.             cell.setCellValue("自定义颜色测试");  
  261.             cellStyle = wb.createCellStyle();  
  262.             // ## 设置填充前景色为LIME ##//  
  263.             cellStyle.setFillForegroundColor(HSSFColor.LIME.index);  
  264.             // ## 设置填充模式为SOLID FOREGROUND ##//  
  265.             cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  266.             font = wb.createFont();  
  267.             // ## 设置字体颜色为红色 ##//  
  268.             font.setColor(HSSFColor.RED.index);  
  269.             cellStyle.setFont(font);  
  270.             cell.setCellStyle(cellStyle);  
  271.   
  272.   
  273.             /* 
  274.              * cell.setCellValue("自定义颜色测试Palette"); //creating a custom palette 
  275.              * for the workbook HSSFPalette palette = 
  276.              * ((HSSFWorkbook)wb).getCustomPalette(); //replacing the standard 
  277.              * red with freebsd.org red 
  278.              * palette.setColorAtIndex(HSSFColor.RED.index, (byte) 153, //RGB 
  279.              * red (0-255) (byte) 0, //RGB green (byte) 0 //RGB blue ); 
  280.              * //replacing lime with freebsd.org gold 
  281.              * palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 
  282.              * 204, (byte) 102); 
  283.              */  
  284.   
  285.   
  286.             /** 第九行 --- 换行 **/  
  287.             Row row9 = sheet.createRow(8);  
  288.             cell = row9.createCell(2);  
  289.             cell.setCellValue("使用 /n及Word-wrap创建一个新行");  
  290.             cellStyle = wb.createCellStyle();  
  291.             // ## 设置WrapText为true ##//  
  292.             cellStyle.setWrapText(true);  
  293.             cell.setCellStyle(cellStyle);  
  294.             // ## 设置行的高度以适应新行 ---两行##//  
  295.             row9.setHeightInPoints((2 * sheet.getDefaultRowHeightInPoints()));  
  296.             // ## 调整列宽 ##//  
  297.             sheet.autoSizeColumn(2);  
  298.   
  299.   
  300.             /** 第十行 --- 数据格式 **/  
  301.             DataFormat format = wb.createDataFormat();  
  302.   
  303.   
  304.             Row row10 = sheet.createRow(9);  
  305.             cell = row10.createCell(0);  
  306.             cell.setCellValue(11111.25);  
  307.             cellStyle = wb.createCellStyle();  
  308.             // ## 一位小数 ##//  
  309.             cellStyle.setDataFormat(format.getFormat("0.0"));  
  310.             cell.setCellStyle(cellStyle);  
  311.   
  312.   
  313.             cell = row10.createCell(1);  
  314.             cell.setCellValue(11111.25);  
  315.             cellStyle = wb.createCellStyle();  
  316.             // ## 四位小数,千位逗号隔开 ##//  
  317.             // #,###.0000效果一样  
  318.             cellStyle.setDataFormat(format.getFormat("#,##0.0000"));  
  319.             cell.setCellStyle(cellStyle);  
  320.   
  321.   
  322.             // ## 将文件写到硬盘上 ##//  
  323.             fileOut = new FileOutputStream(XLS_WORKBOOK_LOCATION);  
  324.             wb.write(fileOut);  
  325.             fileOut.close();  
  326.         } catch (FileNotFoundException e) {  
  327.             e.printStackTrace();  
  328.         } catch (IOException e) {  
  329.             e.printStackTrace();  
  330.         }  
  331.   
  332.   
  333.         /** 
  334.          * EXCEL 2007及以后 
  335.          */  
  336.         /* 
  337.          * try { wb = new XSSFWorkbook(); wb.createSheet("sheet1"); Cell cell = 
  338.          * row.createCell( 0); cell.setCellValue("custom XSSF colors"); 
  339.          * CellStyle style1 = wb.createCellStyle(); 
  340.          * style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 
  341.          * 0, 128))); style1.setFillPattern(CellStyle.SOLID_FOREGROUND); fileOut 
  342.          * = new FileOutputStream("d:/workbook.xlsx"); wb.write(fileOut); 
  343.          * fileOut.close(); } catch (FileNotFoundException e) { 
  344.          * e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 
  345.          */  
  346.   
  347.   
  348.     }  
  349.   
  350.   
  351.     /** 
  352.      * 创建相应格式的CELL 
  353.      */  
  354.     public void createCell(Workbook wb, Row row, short column, short halign,  
  355.             short valign) {  
  356.         Cell cell = row.createCell(column);  
  357.         // ## 给CELL赋值 ##//  
  358.         cell.setCellValue("对齐排列");  
  359.         CellStyle cellStyle = wb.createCellStyle();  
  360.         // ## 设置水平对齐方式 ##//  
  361.         cellStyle.setAlignment(halign);  
  362.         // ## 设置垂直对齐方式 ##//  
  363.         cellStyle.setVerticalAlignment(valign);  
  364.         // ## 添加CELL样式 ##//  
  365.         cell.setCellStyle(cellStyle);  
  366.     }  
  367.   
  368.   
  369.     /** 
  370.      * 测试POI EXCEL迭代和或CELL中的值 
  371.      */  
  372.     @Test  
  373.     public void testExcelIteratorAndCellContents() {  
  374.         try {  
  375.             // ## 创建HSSFWorkbook实例 ##//  
  376.             Workbook wb = new HSSFWorkbook(new FileInputStream(  
  377.                     XLS_WORKBOOK_LOCATION));  
  378.             // ## 获得第一个SHEET ##//  
  379.             Sheet sheet = wb.getSheetAt(0); // or we could cast into  
  380.             // HSSFSheet,that doesn't matter  
  381.             /** 第一种迭代方法 **/  
  382.             /* 
  383.              * //## 迭代ROW ##// for (Iterator<Row> rit = sheet.rowIterator(); 
  384.              * rit.hasNext(); ) { Row row = rit.next(); //## 迭代CELL ##// for 
  385.              * (Iterator<Cell> cit = row.cellIterator(); cit.hasNext(); ) { Cell 
  386.              * cell = cit.next(); System.out.println(cell); } } 
  387.              */  
  388.             /** 第二种迭代方法 **/  
  389.             for (Row row : sheet) {  
  390.                 for (Cell cell : row) {  
  391.                     // ## 获取CellReference对象 ##/  
  392.                     CellReference cellRef = new CellReference(row.getRowNum(),  
  393.                             cell.getColumnIndex());  
  394.                     System.out.print(cellRef.formatAsString());  
  395.                     System.out.print(" - ");  
  396.                     // ## 根据CELL值类型进行相应处理 ##/  
  397.                     switch (cell.getCellType()) {  
  398.                     case Cell.CELL_TYPE_STRING:  
  399.                         System.out.println(cell.getRichStringCellValue()  
  400.                                 .getString());  
  401.                         break;  
  402.                     case Cell.CELL_TYPE_NUMERIC:  
  403.                         // ## yyyy年mm月dd日 hh:mm:ss此种格式日期不能识别 ##//  
  404.                         // ## mm/dd/yyyy h:mm,yyyy-MM-dd  
  405.                         // hh:mm:ss可以识别,估计是POI对中文日期支持不怎么好的问题 ##//  
  406.                         if (DateUtil.isCellDateFormatted(cell)) {  
  407.                             System.out.println(cell.getDateCellValue());  
  408.                         } else {  
  409.                             System.out.println(cell.getNumericCellValue());  
  410.                         }  
  411.                         break;  
  412.                     case Cell.CELL_TYPE_BOOLEAN:  
  413.                         System.out.println(cell.getBooleanCellValue());  
  414.                         break;  
  415.                     case Cell.CELL_TYPE_FORMULA:  
  416.                         System.out.println(cell.getCellFormula());  
  417.                         break;  
  418.                     case Cell.CELL_TYPE_ERROR:  
  419.                         System.out.println(cell.getErrorCellValue());  
  420.                         break;  
  421.                     default:  
  422.                         System.out.println();  
  423.                     }  
  424.                 }  
  425.             }  
  426.   
  427.   
  428.         } catch (FileNotFoundException e) {  
  429.             e.printStackTrace();  
  430.         } catch (IOException e) {  
  431.             e.printStackTrace();  
  432.         }  
  433.     }  
  434.   
  435.   
  436.     /** 
  437.      * 修改文件测试 
  438.      */  
  439.     @Test  
  440.     public void testReadingAndRewritingWorkbooks() {  
  441.         InputStream inp = null;  
  442.         try {  
  443.             inp = new FileInputStream(XLS_WORKBOOK_LOCATION);  
  444.             // inp = new FileInputStream("workbook.xlsx");  
  445.             // ## 获得要修改的Workbook ##/  
  446.             Workbook wb = WorkbookFactory.create(inp);  
  447.             // ## 获取要修改的Sheet ##//  
  448.             Sheet sheet = wb.getSheetAt(0);  
  449.             // ## 获取要修改的Row ##//  
  450.             Row row = sheet.getRow(1);  
  451.             // ## 获取要修改的Cell,如果没有相应位置的Cell那么就创建一个 ##//  
  452.             Cell cell = row.getCell(2);  
  453.             if (cell == null)  
  454.                 cell = row.createCell(2);  
  455.             // ## 写入修改数据 ##//  
  456.             cell.setCellType(Cell.CELL_TYPE_STRING);  
  457.             cell.setCellValue("修改文件测试");  
  458.   
  459.   
  460.             // ## 将文件写到硬盘上 ##//  
  461.             FileOutputStream fileOut = new FileOutputStream(  
  462.                     XLS_WORKBOOK_LOCATION);  
  463.             wb.write(fileOut);  
  464.             fileOut.close();  
  465.         } catch (FileNotFoundException e) {  
  466.             e.printStackTrace();  
  467.         } catch (InvalidFormatException e) {  
  468.             e.printStackTrace();  
  469.         } catch (IOException e) {  
  470.             e.printStackTrace();  
  471.         }  
  472.     }  
  473.   
  474.   
  475.     /** 
  476.      * 暂时没看到有什么区别 
  477.      */  
  478.     @Test  
  479.     public void testFitSheetToOnePage() {  
  480.         try {  
  481.             Workbook wb = new HSSFWorkbook();  
  482.             Sheet sheet = wb.createSheet("format sheet");  
  483.             PrintSetup ps = sheet.getPrintSetup();  
  484.   
  485.   
  486.             sheet.setAutobreaks(true);  
  487.   
  488.   
  489.             ps.setFitHeight((short1);  
  490.             ps.setFitWidth((short1);  
  491.             // Create various cells and rows for spreadsheet.  
  492.             FileOutputStream fileOut = new FileOutputStream(  
  493.                     XLS_WORKBOOK_LOCATION);  
  494.             wb.write(fileOut);  
  495.             fileOut.close();  
  496.         } catch (Exception e) {  
  497.             e.printStackTrace();  
  498.         }  
  499.     }  
  500.   
  501.   
  502.     /** 
  503.      * 设置打印区域测试 
  504.      */  
  505.     @Test  
  506.     public void testSetPrintArea() {  
  507.         /** 
  508.          * 注意:我测试的时候用的是EXCEL 2007打开的,效果不明显,只能控制列且列好像也是不正确的。 但是我用EXCEL 
  509.          * 2007转换了一下,xls,xlsx的都正确了,目前还不知道是什么问题。 
  510.          */  
  511.         try {  
  512.             Workbook wb = new HSSFWorkbook();  
  513.             Sheet sheet = wb.createSheet("Print Area Sheet");  
  514.             Row row = sheet.createRow(0);  
  515.             row.createCell(0).setCellValue("第一个单元格");  
  516.             row.createCell(1).setCellValue("第二个单元格");  
  517.             row.createCell(2).setCellValue("第三个单元格");  
  518.             row = sheet.createRow(1);  
  519.             row.createCell(0).setCellValue("第四个单元格");  
  520.             row.createCell(1).setCellValue("第五个单元格");  
  521.             row = sheet.createRow(2);  
  522.             row.createCell(0).setCellValue("第六个单元格");  
  523.             row.createCell(1).setCellValue("第七个单元格");  
  524.             // ## 设置打印区域 A1--C2 ##//  
  525.             // wb.setPrintArea(0, "$A$1:$C$2");  
  526.             // ## 或者使用以下方法设置 ##//  
  527.             wb.setPrintArea(0// Sheet页  
  528.                     0// 开始列  
  529.                     2// 结束列  
  530.                     0// 开始行  
  531.                     1// 结束行  
  532.                     );  
  533.   
  534.   
  535.             FileOutputStream fileOut = new FileOutputStream(  
  536.                     XLS_WORKBOOK_LOCATION);  
  537.             wb.write(fileOut);  
  538.             fileOut.close();  
  539.         } catch (FileNotFoundException e) {  
  540.             e.printStackTrace();  
  541.         } catch (IOException e) {  
  542.             e.printStackTrace();  
  543.         }  
  544.   
  545.   
  546.     }  
  547.   
  548.   
  549.     /** 
  550.      * 设置页脚测试 用“页面布局”可以看到效果 下列代码只适用xls 
  551.      */  
  552.     @Test  
  553.     public void testSetPageNumbersOnFooter() {  
  554.         try {  
  555.             HSSFWorkbook wb = new HSSFWorkbook();  
  556.             HSSFSheet sheet = wb.createSheet("Footer Test");  
  557.             // ## 获得页脚 ##/  
  558.             HSSFFooter footer = sheet.getFooter();  
  559.             Row row;  
  560.             // ## 将 当前页/总页数 写在右边 ##/  
  561.             footer.setRight(HSSFFooter.page() + "/" + HSSFFooter.numPages());  
  562.             for (int i = 0; i < 100; i++) {  
  563.                 row = sheet.createRow(i);  
  564.                 for (int j = 0; j < 20; j++) {  
  565.                     row.createCell(j).setCellValue("A" + i + j);  
  566.                 }  
  567.             }  
  568.             FileOutputStream fileOut = new FileOutputStream(  
  569.                     XLS_WORKBOOK_LOCATION);  
  570.             wb.write(fileOut);  
  571.             fileOut.close();  
  572.         } catch (FileNotFoundException e) {  
  573.             e.printStackTrace();  
  574.         } catch (IOException e) {  
  575.             e.printStackTrace();  
  576.         }  
  577.   
  578.   
  579.     }  
  580.   
  581.   
  582.     /** 
  583.      * 测试一些POI提供的比较方便的函数 文档中有些以HSSF为前缀的类的方法以过时(e.g: HSSFSheet, HSSFCell etc.), 
  584.      * 测试的时候我去掉了HSSF前缀,当然也就是现在POI推荐的接口(Sheet,Row,Cell etc.) 
  585.      */  
  586.     @Test  
  587.     public void testConvenienceFunctions() {  
  588.         try {  
  589.             Workbook wb = new HSSFWorkbook();  
  590.             Sheet sheet1 = wb.createSheet("Convenience Functions");  
  591.             // ## 设置Sheet的显示比例 这里是3/4,也就是 75% ##//  
  592.             sheet1.setZoom(34);  
  593.             // ## 合并单元格 ##//  
  594.             Row row = sheet1.createRow((short1);  
  595.             Row row2 = sheet1.createRow((short2);  
  596.             Cell cell = row.createCell((short1);  
  597.             cell.setCellValue("合并单元格测试");  
  598.             // ## 创建合并区域 ##//  
  599.             CellRangeAddress region = new CellRangeAddress(1, (short14,  
  600.                     (short4);  
  601.             sheet1.addMergedRegion(region);  
  602.   
  603.   
  604.             // ## 设置边框及边框颜色 ##//  
  605.             final short borderMediumDashed = CellStyle.BORDER_MEDIUM_DASHED;  
  606.             RegionUtil.setBorderBottom(borderMediumDashed, region, sheet1, wb);  
  607.             RegionUtil.setBorderTop(borderMediumDashed, region, sheet1, wb);  
  608.             RegionUtil.setBorderLeft(borderMediumDashed, region, sheet1, wb);  
  609.             RegionUtil.setBorderRight(borderMediumDashed, region, sheet1, wb);  
  610.             // ## 设置底部边框的颜色 ##//  
  611.             RegionUtil.setBottomBorderColor(HSSFColor.AQUA.index, region,  
  612.                     sheet1, wb);  
  613.             // ## 设置顶部边框的颜色 ##//  
  614.             RegionUtil.setTopBorderColor(HSSFColor.AQUA.index, region, sheet1,  
  615.                     wb);  
  616.             // ## 设置左边边框的颜色 ##//  
  617.             RegionUtil.setLeftBorderColor(HSSFColor.AQUA.index, region, sheet1,  
  618.                     wb);  
  619.             // ## 设置右边边框的颜色 ##//  
  620.             RegionUtil.setRightBorderColor(HSSFColor.AQUA.index, region,  
  621.                     sheet1, wb);  
  622.   
  623.   
  624.             // ## CellUtil的一些用法 ##/  
  625.             CellStyle style = wb.createCellStyle();  
  626.             style.setIndention((short10);  
  627.             CellUtil.createCell(row, 8"CellUtil测试", style);  
  628.             Cell cell2 = CellUtil.createCell(row2, 8"CellUtil测试");  
  629.             // ## 设置对齐方式为居中对齐 ##//  
  630.             CellUtil.setAlignment(cell2, wb, CellStyle.ALIGN_CENTER);  
  631.   
  632.   
  633.             // ## 将Workbook写到硬盘上 ##//  
  634.             FileOutputStream fileOut = new FileOutputStream(  
  635.                     XLS_WORKBOOK_LOCATION);  
  636.             wb.write(fileOut);  
  637.             fileOut.close();  
  638.         } catch (FileNotFoundException e) {  
  639.             e.printStackTrace();  
  640.         } catch (IOException e) {  
  641.             e.printStackTrace();  
  642.         }  
  643.     }  
  644.   
  645.   
  646.     /** 
  647.      * 测试冻结窗格和拆分 
  648.      */  
  649.     @Test  
  650.     public void testSplitAndFreezePanes() {  
  651.         try {  
  652.             Workbook wb = new HSSFWorkbook();  
  653.             Sheet sheet1 = wb.createSheet("冻结首行Sheet");  
  654.             Sheet sheet2 = wb.createSheet("冻结首列Sheet");  
  655.             Sheet sheet3 = wb.createSheet("冻结两行两列 Sheet");  
  656.             Sheet sheet4 = wb.createSheet("拆分Sheet");  
  657.   
  658.   
  659.             /** 冻结窗格 **/  
  660.             /* 
  661.              * createFreezePane( colSplit, rowSplit, topRow, leftmostColumn ) 
  662.              * colSplit 冻结线水平位置 rowSplit 冻结线垂直位置 topRow Top row visible in 
  663.              * bottom pane leftmostColumn Left column visible in right pane. 
  664.              */  
  665.             // ## 冻结首行 ##//  
  666.             sheet1.createFreezePane(0101);  
  667.             // ## 冻结首列 ##//  
  668.             sheet2.createFreezePane(1010);  
  669.             // ## 冻结两行两列 ##//  
  670.             sheet3.createFreezePane(22);  
  671.             // ## 拆分,左下的为面板为激活状态 ##//  
  672.             sheet4.createSplitPane(2000200000, Sheet.PANE_LOWER_LEFT);  
  673.   
  674.   
  675.             FileOutputStream fileOut = new FileOutputStream(  
  676.                     XLS_WORKBOOK_LOCATION);  
  677.             wb.write(fileOut);  
  678.             fileOut.close();  
  679.         } catch (FileNotFoundException e) {  
  680.             e.printStackTrace();  
  681.         } catch (IOException e) {  
  682.             e.printStackTrace();  
  683.         }  
  684.     }  
  685.   
  686.   
  687.     /** 
  688.      * 测试简单图形 
  689.      */  
  690.     @Test  
  691.     public void testDrawingShapes() {  
  692.         try {  
  693.             Workbook wb = new HSSFWorkbook();  
  694.             Sheet sheet = wb.createSheet("Drawing Shapes");  
  695.             // ## 得到一个HSSFPatriarch对象,有点像画笔但是注意区别 ##//  
  696.             HSSFPatriarch patriarch = (HSSFPatriarch) sheet  
  697.                     .createDrawingPatriarch();  
  698.             /* 
  699.              * 构造器: HSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, short 
  700.              * col1, int row1, short col2, int row2) 描述: 
  701.              * 创建HSSFClientAnchor类的实例,设置该anchor的顶-左和底-右坐标(相当于锚点,也就是图像出现的位置,大小等). 
  702.              * Creates a new client anchor and sets the top-left and 
  703.              * bottom-right coordinates of the anchor. 参数: dx1 第一个单元格的x坐标 dy1 
  704.              * 第一个单元格的y坐标 dx2 第二个单元格的x坐标 dy2 第二个单元格的y坐标 col1 第一个单元格所在列 row1 
  705.              * 第一个单元格所在行 col2 第二个单元格所在列 row2 第二个单元格所在行 
  706.              */  
  707.             HSSFClientAnchor anchor = new HSSFClientAnchor(00512255,  
  708.                     (short10, (short10);  
  709.             // ## 通过HSSFClientAnchor类的对象创建HSSFSimpleShape的实例 ##//  
  710.             HSSFSimpleShape shape = patriarch.createSimpleShape(anchor);  
  711.             // ## 画个椭圆 ##//  
  712.             shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);  
  713.   
  714.   
  715.             // ## 这几个是没问题的 ##//  
  716.             // shape.setLineStyleColor(10,10,10);  
  717.             // shape.setFillColor(90,10,200);  
  718.             // shape.setLineStyleColor(HSSFColor.BLUE.index); //设置不了,尚不知原因  
  719.             // ## 设置线条颜色为红色 ##//  
  720.             // shape.setLineStyleColor(Color.BLUE.getRGB()); //搞不清楚为什是反的BLUE:红色  
  721.             // RED:蓝色,是不是开发POI的有点色盲,JUST KIDDING!  
  722.             // ## 设置填充颜色为灰色 ##//  
  723.             shape.setFillColor(Color.GRAY.getRGB()); // 这个又可以  
  724.             // ## 设置线条宽度为3pt ##//  
  725.             shape.setLineWidth(HSSFShape.LINEWIDTH_ONE_PT * 3);  
  726.             // ## 设置线条的样式为点式 ##//  
  727.             shape.setLineStyle(HSSFShape.LINESTYLE_DOTSYS);  
  728.   
  729.   
  730.             // ## 创建文本框并填充文字 “创建文本框” ##//  
  731.             HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor(  
  732.                     0000, (short11, (short22));  
  733.             RichTextString text = new HSSFRichTextString("创建文本框");  
  734.             // ## 创建字体 ##//  
  735.             Font font = wb.createFont();  
  736.             // ## 斜体 ##//  
  737.             font.setItalic(true);  
  738.             // ## 设置字体颜色为蓝色 ##//  
  739.             // font.setColor((short)Color.BLUE.getBlue()); not work  
  740.             font.setColor(HSSFColor.BLUE.index);  
  741.             // ## 添加字体 ##//  
  742.             text.applyFont(font);  
  743.             textbox.setString(text);  
  744.   
  745.   
  746.             // ## 将文件写到硬盘上 ##//  
  747.             FileOutputStream fileOut = new FileOutputStream(  
  748.                     XLS_WORKBOOK_LOCATION);  
  749.             wb.write(fileOut);  
  750.             fileOut.close();  
  751.         } catch (FileNotFoundException e) {  
  752.             e.printStackTrace();  
  753.         } catch (IOException e) {  
  754.             e.printStackTrace();  
  755.         }  
  756.     }  
  757.   
  758.   
  759.     /** 
  760.      * 添加图片到工作薄测试 已测试PNG,JPG,GIF 
  761.      */  
  762.     @Test  
  763.     public void testImages() {  
  764.         try {  
  765.             // ## 创建一个新的工作薄 ##//  
  766.             Workbook wb = new XSSFWorkbook(); // or new HSSFWorkbook();  
  767.   
  768.   
  769.             // ## 添加图片到该工作薄 ##//  
  770.             InputStream is = new FileInputStream(IMAGE_LOCATION);  
  771.             byte[] bytes = IOUtils.toByteArray(is);  
  772.             int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);  
  773.             is.close();  
  774.   
  775.   
  776.             CreationHelper helper = wb.getCreationHelper();  
  777.   
  778.   
  779.             // ## 创建一个名为“添加图片”的Sheet ##//  
  780.             Sheet sheet = wb.createSheet("添加图片");  
  781.   
  782.   
  783.             // ## 创建一个DrawingPatriarch实例 ##//  
  784.             Drawing drawing = sheet.createDrawingPatriarch();  
  785.   
  786.   
  787.             // ## 设置图片的形状,位置等 ##//  
  788.             ClientAnchor anchor = helper.createClientAnchor();  
  789.             // set top-left corner of the picture,  
  790.             // subsequent call of Picture#resize() will operate relative to it  
  791.             anchor.setCol1(3);  
  792.             anchor.setRow1(2);  
  793.             Picture pict = drawing.createPicture(anchor, pictureIdx);  
  794.             // ## 自动设置图片的大小 注意:只支持PNG,JPG,GIF(BMP未测试)##//  
  795.             pict.resize();  
  796.   
  797.   
  798.             // ## 保存Workbook ##//  
  799.             String file = "picture.xls";  
  800.             if (wb instanceof XSSFWorkbook)  
  801.                 file += "x";  
  802.             FileOutputStream fileOut = new FileOutputStream(XLS_OR_XLSX_DIR  
  803.                     + file);  
  804.             wb.write(fileOut);  
  805.             fileOut.close();  
  806.         } catch (FileNotFoundException e) {  
  807.             e.printStackTrace();  
  808.         } catch (IOException e) {  
  809.             e.printStackTrace();  
  810.         }  
  811.   
  812.   
  813.     }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值