Excel之POI转自http://xiayingjie.iteye.com/blog/803682

java操作Excel最常用的开源组件有poi与jxl。jxl是韩国人开发的,发行较早,但是更新的很慢,目前似乎还不支持excel2007。poi是apache下的一个子项目,poi应该是处理ms的office系列文档最好的组件了。poi3.7版本已经开始支持excel2007了。但是由于excel2007底层的实现似乎变成xml与excel2003底层存储发生了本质的变化,因此poi解析excel的类就存在差异了。
      现在简单的介绍下poi常用的接口。
      经常用的类一般都在org.apache.poi.hssf.usermodel(excel2003)或org.apache.poi.xssf.usermodel
(excel2007)。
工作薄:  WorkBook是操作Excel的入口,HSSFWorkbook, XSSFWorkbook实现了该接口。
页:Sheet表示工作薄的分页。HSSFSheet, XSSFChartSheet, XSSFDialogsheet, XSSFSheet实现了该接口。
Row:表示页中的一行。HSSFRow, XSSFRow实现了该接口。
Cell:行中的一个单元格。HSSFCell, XSSFCell实现了该接口

下面是个人写的一个通用类 使用的是POI3.7

Java代码   收藏代码
  1. package com.xyj.com.tool.util;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import java.util.Calendar;  
  10. import java.util.HashMap;  
  11. import java.util.Map;  
  12.   
  13. import org.apache.commons.io.IOUtils;  
  14. import org.apache.poi.hssf.usermodel.HSSFCell;  
  15. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  16. import org.apache.poi.hssf.usermodel.HSSFFont;  
  17. import org.apache.poi.hssf.usermodel.HSSFPalette;  
  18. import org.apache.poi.hssf.usermodel.HSSFRow;  
  19. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  20. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  21. import org.apache.poi.hssf.util.HSSFColor;  
  22. import org.apache.poi.ss.extractor.ExcelExtractor;  
  23. import org.apache.poi.ss.usermodel.Cell;  
  24. import org.apache.poi.ss.usermodel.CellStyle;  
  25. import org.apache.poi.ss.usermodel.ClientAnchor;  
  26. import org.apache.poi.ss.usermodel.CreationHelper;  
  27. import org.apache.poi.ss.usermodel.DateUtil;  
  28. import org.apache.poi.ss.usermodel.Drawing;  
  29. import org.apache.poi.ss.usermodel.Font;  
  30. import org.apache.poi.ss.usermodel.Footer;  
  31. import org.apache.poi.ss.usermodel.IndexedColors;  
  32. import org.apache.poi.ss.usermodel.Picture;  
  33. import org.apache.poi.ss.usermodel.Row;  
  34. import org.apache.poi.ss.usermodel.Sheet;  
  35. import org.apache.poi.ss.usermodel.Workbook;  
  36. import org.apache.poi.ss.usermodel.WorkbookFactory;  
  37. import org.apache.poi.ss.util.CellRangeAddress;  
  38. import org.apache.poi.ss.util.CellReference;  
  39. import org.apache.poi.xssf.extractor.XSSFExcelExtractor;  
  40. import org.apache.poi.xssf.usermodel.XSSFCellStyle;  
  41. import org.apache.poi.xssf.usermodel.XSSFColor;  
  42. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  43.   
  44. /** 
  45.  * @className:POIExcelUtil.java 
  46.  * @classDescription:POI操作类 
  47.  * @author:xiayingjie 
  48.  * @createTime:2010-10-29 
  49.  */  
  50.   
  51. public class POIExcelUtil {  
  52.   
  53.     // ------------------------写Excel-----------------------------------  
  54.     /** 
  55.      * 创建workBook对象 xlsx(2007以上版本) 
  56.      *  
  57.      * @return 
  58.      */  
  59.     public static Workbook createWorkbook() {  
  60.         return createWorkbook(true);  
  61.     }  
  62.   
  63.     /** 
  64.      * 创建WorkBook对象 
  65.      *  
  66.      * @param flag 
  67.      *            true:xlsx(1997-2007) false:xls(2007以上) 
  68.      * @return 
  69.      */  
  70.     public static Workbook createWorkbook(boolean flag) {  
  71.         Workbook wb;  
  72.         if (flag) {  
  73.             wb = new XSSFWorkbook();  
  74.         } else {  
  75.             wb = new HSSFWorkbook();  
  76.         }  
  77.         return wb;  
  78.     }  
  79.   
  80.     /** 
  81.      * 添加图片 
  82.      *  
  83.      * @param wb 
  84.      *            workBook对象 
  85.      * @param sheet 
  86.      *            sheet对象 
  87.      * @param picFileName 
  88.      *            图片文件名称(全路径) 
  89.      * @param picType 
  90.      *            图片类型 
  91.      * @param row 
  92.      *            图片所在的行 
  93.      * @param col 
  94.      *            图片所在的列 
  95.      */  
  96.     public static void addPicture(Workbook wb, Sheet sheet, String picFileName,  
  97.             int picType, int row, int col) {  
  98.         InputStream is = null;  
  99.         try {  
  100.             // 读取图片  
  101.             is = new FileInputStream(picFileName);  
  102.             byte[] bytes = IOUtils.toByteArray(is);  
  103.             int pictureIdx = wb.addPicture(bytes, picType);  
  104.             is.close();  
  105.             // 写图片  
  106.             CreationHelper helper = wb.getCreationHelper();  
  107.             Drawing drawing = sheet.createDrawingPatriarch();  
  108.             ClientAnchor anchor = helper.createClientAnchor();  
  109.             // 设置图片的位置  
  110.             anchor.setCol1(col);  
  111.             anchor.setRow1(row);  
  112.             Picture pict = drawing.createPicture(anchor, pictureIdx);  
  113.   
  114.             pict.resize();  
  115.         } catch (Exception e) {  
  116.             try {  
  117.                 if (is != null) {  
  118.                     is.close();  
  119.                 }  
  120.             } catch (IOException e1) {  
  121.                 e1.printStackTrace();  
  122.             }  
  123.             e.printStackTrace();  
  124.         }  
  125.     }  
  126.   
  127.     /** 
  128.      * 创建Cell 默认为水平和垂直方式都是居中 
  129.      *  
  130.      * @param style 
  131.      *            CellStyle对象 
  132.      * @param row 
  133.      *            Row对象 
  134.      * @param column 
  135.      *            单元格所在的列 
  136.      * @return 
  137.      */  
  138.     public static Cell createCell(CellStyle style, Row row, short column) {  
  139.         return createCell(style, row,  column,  
  140.                 XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.ALIGN_CENTER);  
  141.     }  
  142.   
  143.     /** 
  144.      * 创建Cell并设置水平和垂直方式 
  145.      *  
  146.      * @param style 
  147.      *            CellStyle对象 
  148.      * @param row 
  149.      *            Row对象 
  150.      * @param column 
  151.      *            单元格所在的列 
  152.      * @param halign 
  153.      *            水平对齐方式:XSSFCellStyle.VERTICAL_CENTER. 
  154.      * @param valign 
  155.      *            垂直对齐方式:XSSFCellStyle.ALIGN_LEFT 
  156.      */  
  157.     public static Cell createCell(CellStyle style, Row row,   
  158.             short column, short halign, short valign) {  
  159.         Cell cell = row.createCell(column);  
  160.         setAlign(style,halign,valign);  
  161.         cell.setCellStyle(style);  
  162.         return cell;  
  163.     }  
  164.       
  165.     /** 
  166.      * 合并单元格 
  167.      * @param sheet 
  168.      * @param firstRow 开始行 
  169.      * @param lastRow 最后行 
  170.      * @param firstCol 开始列 
  171.      * @param lastCol 最后列 
  172.      */  
  173.     public static void mergeCell(Sheet sheet,int firstRow,int lastRow,int firstCol,int lastCol){  
  174.          sheet.addMergedRegion(new CellRangeAddress(firstRow,lastRow,firstCol,lastCol));  
  175.     }  
  176.       
  177.     //---------------------------------设置样式-----------------------  
  178.       
  179.     /** 
  180.      * 设置单元格对齐方式 
  181.      * @param style 
  182.      * @param halign 
  183.      * @param valign 
  184.      * @return 
  185.      */  
  186.     public static CellStyle setAlign(CellStyle style,short halign, short valign) {  
  187.         style.setAlignment(halign);  
  188.         style.setVerticalAlignment(valign);  
  189.         return style;  
  190.     }  
  191.       
  192.     /** 
  193.      * 设置单元格边框(四个方向的颜色一样) 
  194.      * @param style style对象 
  195.      * @param borderStyle 边框类型 :dished-虚线 thick-加粗 double-双重 dotted-有点的 CellStyle.BORDER_THICK 
  196.      * @param borderColor 颜色 IndexedColors.GREEN.getIndex() 
  197.      * @return 
  198.      */  
  199.     public static CellStyle setBorder(CellStyle style,short borderStyle,short borderColor){  
  200.           
  201.         //设置底部格式(样式+颜色)  
  202.         style.setBorderBottom(borderStyle);  
  203.         style.setBottomBorderColor(borderColor);  
  204.         //设置左边格式  
  205.         style.setBorderLeft(borderStyle);  
  206.         style.setLeftBorderColor(borderColor);  
  207.         //设置右边格式  
  208.         style.setBorderRight(borderStyle);  
  209.         style.setRightBorderColor(borderColor);  
  210.         //设置顶部格式  
  211.         style.setBorderTop(borderStyle);  
  212.         style.setTopBorderColor(borderColor);  
  213.           
  214.         return style;  
  215.     }  
  216.       
  217.       
  218.     /** 
  219.      * 自定义颜色(xssf) 
  220.      * @param style  xssfStyle 
  221.      * @param red RGB red (0-255) 
  222.      * @param green RGB green (0-255) 
  223.      * @param blue RGB blue (0-255) 
  224.      */  
  225.     public static CellStyle setBackColorByCustom(XSSFCellStyle style,int red ,int green,int blue){         
  226.             //设置前端颜色  
  227.             style.setFillForegroundColor(new XSSFColor(new java.awt.Color(red, green, blue)));  
  228.             //设置填充模式  
  229.             style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  230.               
  231.             return style;  
  232.     }  
  233.     /** 
  234.      * 设置前景颜色 
  235.      * @param style style对象 
  236.      * @param color :IndexedColors.YELLOW.getIndex() 
  237.      * @return 
  238.      */  
  239.     public static CellStyle setBackColor(CellStyle style,short color){  
  240.   
  241.        //设置前端颜色  
  242.         style.setFillForegroundColor(color);  
  243.         //设置填充模式  
  244.         style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  245.   
  246.         return style;  
  247.     }  
  248.       
  249.       
  250.       
  251.     /** 
  252.      * 设置背景颜色 
  253.      * @param style style对象 
  254.      * @param color :IndexedColors.YELLOW.getIndex() 
  255.      * @param fillPattern :CellStyle.SPARSE_DOTS 
  256.      * @return 
  257.      */  
  258.     public static CellStyle setBackColor(CellStyle style,short backColor,short fillPattern){  
  259.   
  260.         //设置背景颜色  
  261.         style.setFillBackgroundColor(backColor);  
  262.          
  263.         //设置填充模式  
  264.         style.setFillPattern(fillPattern);  
  265.           
  266.         return style;  
  267.     }  
  268.       
  269.     /** 
  270.      *  
  271.      * 设置字体(简单的需求实现,如果复杂的字体,需要自己去实现)尽量重用 
  272.      * @param style style对象 
  273.      * @param fontSize 字体大小 shot(24) 
  274.      * @param color 字体颜色  IndexedColors.YELLOW.getIndex() 
  275.      * @param fontName 字体名称 "Courier New" 
  276.      * @param  
  277.      */  
  278.     public static CellStyle setFont(Font font, CellStyle style,short fontSize,short color,String fontName){  
  279.             font.setFontHeightInPoints(color);  
  280.             font.setFontName(fontName);  
  281.               
  282.             //font.setItalic(true);// 斜体  
  283.             //font.setStrikeout(true);//加干扰线  
  284.               
  285.             font.setColor(color);//设置颜色  
  286.             // Fonts are set into a style so create a new one to use.  
  287.             style.setFont(font);  
  288.                           
  289.             return style;  
  290.   
  291.     }  
  292.   
  293.   
  294.     /** 
  295.      *  
  296.      * @param createHelper 
  297.      *            createHelper对象 
  298.      * @param style 
  299.      *            CellStyle对象 
  300.      * @param formartData 
  301.      *            date:"m/d/yy h:mm"; int:"#,###.0000" ,"0.0" 
  302.      */  
  303.     public static CellStyle setDataFormat(CreationHelper createHelper, CellStyle style, String formartData) {  
  304.           
  305.         style.setDataFormat(createHelper.createDataFormat().getFormat(  
  306.                 formartData));  
  307.       
  308.         return style;  
  309.     }  
  310.   
  311.     /** 
  312.      * 将Workbook写入文件 
  313.      *  
  314.      * @param wb 
  315.      *            workbook对象 
  316.      * @param fileName 
  317.      *            文件的全路径 
  318.      * @return 
  319.      */  
  320.     public static boolean createExcel(Workbook wb, String fileName) {  
  321.         boolean flag = true;  
  322.         FileOutputStream fileOut = null;  
  323.         try {  
  324.             fileOut = new FileOutputStream(fileName);  
  325.             wb.write(fileOut);  
  326.             fileOut.close();  
  327.   
  328.         } catch (Exception e) {  
  329.             flag = false;  
  330.             if (fileOut != null) {  
  331.                 try {  
  332.                     fileOut.close();  
  333.                 } catch (IOException e1) {  
  334.                     // TODO Auto-generated catch block  
  335.                     e1.printStackTrace();  
  336.                 }  
  337.             }  
  338.             e.printStackTrace();  
  339.         }  
  340.         return flag;  
  341.     }  
  342.       
  343.   
  344.     //--------------------读取Excel-----------------------  
  345.     /** 
  346.      * 读取Excel 
  347.      * @param filePathName 
  348.      * @return 
  349.      */  
  350.     public  static Workbook readExcel(String filePathName){  
  351.         InputStream inp = null;  
  352.         Workbook wb=null;  
  353.          try {  
  354.             inp = new FileInputStream(filePathName);  
  355.             wb = WorkbookFactory.create(inp);  
  356.             inp.close();  
  357.              
  358.         } catch (Exception e) {  
  359.             try {  
  360.                 if(null!=inp){  
  361.                     inp.close();  
  362.                 }  
  363.             } catch (IOException e1) {  
  364.                 // TODO Auto-generated catch block  
  365.                 e1.printStackTrace();  
  366.             }  
  367.             e.printStackTrace();  
  368.         }  
  369.          return wb;  
  370.     }  
  371.       
  372.   
  373.       
  374.     /** 
  375.      * 读取Cell的值 
  376.      * @param sheet 
  377.      * @return 
  378.      */  
  379.     public static Map readCell(Sheet sheet){  
  380.         Map map=new HashMap();  
  381.         //遍历所有行  
  382.          for (Row row : sheet) {     
  383.                 //便利所有列  
  384.                 for (Cell cell : row) {   
  385.                     //获取单元格的类型  
  386.                     CellReference cellRef = new CellReference(row.getRowNum(), cell     
  387.                             .getColumnIndex());     
  388.                  //   System.out.print(cellRef.formatAsString());     
  389.                     String key=cellRef.formatAsString();  
  390.                  //   System.out.print(" - ");     
  391.         
  392.                     switch (cell.getCellType()) {    
  393.                     //字符串  
  394.                     case Cell.CELL_TYPE_STRING:     
  395.                          map.put(key, cell.getRichStringCellValue()     
  396.                                       .getString());      
  397.                       //  System.out.println(cell.getRichStringCellValue()     
  398.                           //         .getString());     
  399.                         break;  
  400.                     //数字  
  401.                     case Cell.CELL_TYPE_NUMERIC:     
  402.                         if (DateUtil.isCellDateFormatted(cell)) {     
  403.                           //  System.out.println(cell.getDateCellValue());   
  404.                             map.put(key, cell.getDateCellValue());  
  405.                         } else {     
  406.                           //  System.out.println(cell.getNumericCellValue());    
  407.                             map.put(key, cell.getNumericCellValue());  
  408.                         }     
  409.                         break;     
  410.                     //boolean  
  411.                     case Cell.CELL_TYPE_BOOLEAN:     
  412.                        // System.out.println(cell.getBooleanCellValue());     
  413.                         map.put(key, cell.getBooleanCellValue());  
  414.                         break;    
  415.                     //方程式  
  416.                     case Cell.CELL_TYPE_FORMULA:     
  417.                       // System.out.println(cell.getCellFormula());  
  418.                         map.put(key, cell.getCellFormula());  
  419.                         break;     
  420.                     //空值  
  421.                     default:     
  422.                         System.out.println();    
  423.                         map.put(key,"");  
  424.                     }    
  425.                      
  426.                 }   
  427.          }  
  428.          return map;  
  429.           
  430.     }  
  431.     /** 
  432.      * @param args 
  433.      * @throws Exception 
  434.      */  
  435.     public static void main(String[] args) throws Exception {  
  436.           
  437. //      在需要换行的地方加上\n   cell.setCellValue("Use \n with word wrap on to create a new line");  
  438. //      设置行高 row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));  
  439. //      设置列只适应宽度 sheet.autoSizeColumn((short)2);  
  440.           
  441. //        
  442. //      // -------------插入---------------------  
  443. //      Workbook wb = POIUtil.createWorkbook();  
  444. //      //创建Sheet  
  445. //      Sheet s = wb.createSheet();  
  446. //      s.autoSizeColumn(1);  
  447. //      s.autoSizeColumn(0);  
  448. //      s.autoSizeColumn(2);  
  449. //      //创建样式(真实项目中-所有样式都写在这里)  
  450. //      CellStyle style1=wb.createCellStyle();  
  451. //      CellStyle style2=wb.createCellStyle();  
  452. //      CellStyle style3=wb.createCellStyle();  
  453. //      //字体  
  454. //      //设置字体  
  455. //      Font font=wb.createFont();  
  456. //      CellStyle fontStyle =setFont(font,style3,(short)30,IndexedColors.RED.getIndex() , "Courier New");  
  457. //      //合并单元格  
  458. //      //mergeCell(s,2,2,1,2);  
  459. //      //创建行  
  460. //      Row row1 = s.createRow(0);  
  461. //      row1.setHeightInPoints((2*s.getDefaultRowHeightInPoints()));  
  462. //      //-----------数字-----------  
  463. //      Cell c1=createCell(style1, row1, (short) 0);  
  464. //      c1.setCellValue(3.138);  
  465. //      //设置边框  
  466. //      setBorder(style1,CellStyle.BORDER_THIN,IndexedColors.GREEN.getIndex());  
  467. //    
  468. //    
  469. //      //-------------日期----------------  
  470. //      Cell c2=createCell(style2, row1, (short) 1);  
  471. //      c2.setCellValue(Calendar.getInstance());  
  472. //      CreationHelper ch=wb.getCreationHelper();  
  473. //      setDataFormat(ch,style2,"m/d/yy h:mm");  
  474. //      setBackColor(style2,IndexedColors.YELLOW.getIndex());  
  475. //  
  476. //        
  477. //        
  478. //      Cell c4=createCell(style2, row1, (short) 2);  
  479. //        
  480. //      //----------------字符串------------------  
  481. //        
  482. //      //Cell c3=createCell(style3, row1, (short) 2);  
  483. //      Cell c3=row1.createCell((short) 3);  
  484. //      c3.setCellValue("我和你dfgd、\nfged二个如果");  
  485. //      CellStyle cs=wb.createCellStyle();  
  486. //        
  487. //      setBackColor(style3,IndexedColors.ORANGE.getIndex());     
  488. //    
  489. //        
  490. //      c3.setCellStyle(style3);  
  491.         //c3.setCellStyle(cs);  
  492.         //写入图片  
  493.         // POIUtil.addPicture(wb, s,"F://aa.gif", Workbook.PICTURE_TYPE_JPEG,5,6);  
  494.   
  495. //       Footer footer = s.getFooter();   //页脚  
  496. //          
  497. //      footer.setRight( "Page " + footer.getLeft() + " of " + footer.getRight());   
  498.            
  499. //      s.shiftRows(5, 10,-5); //把第6-11行向上移动5行     
  500. //      s.setSelected(true);  //选中sheet  
  501. //        
  502.          //打印  
  503. //      PrintSetup ps = s.getPrintSetup();     
  504. //          
  505. //      sheet.setAutobreaks(true);     
  506. //      
  507. //      ps.setFitHeight((short)1);     
  508. //      ps.setFitWidth((short)1);   
  509.           
  510. //      POIUtil.createExcel(wb, "F://text.xlsx");  
  511.           
  512.         //=====================读================  
  513.         Workbook wb=readExcel("F://text.xlsx");  
  514.         Map<String,Object> map=readCell(wb.getSheetAt(0));  
  515.         for(String key:map.keySet()){  
  516.             System.out.println(key+"-"+map.get(key));  
  517.         }  
  518.           
  519.   
  520.     }  
  521.   


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值