Java 操作 Excel (读取Excel2003 2007,Poi实现)

来源:互联网 发布:河北广电网络集团电话 编辑:程序博客网 时间:2024/06/02 04:57
原文地址:

http://boendev.iteye.com/blog/758690
ExcelJavaApache单元测试FP
一. Apache POI 简介( http://poi.apache.org/) 

    使用Java程序读写Microsoft Office,提供了下面这几种类型: 

    HSSF-提供读写Microsoft Excel XLS格式档案的功能。 
    XSSF-提供读写Microsoft Excel OOXML XLSX格式档案的功能。 
    HWPF-提供读写Microsoft Word DOC格式档案的功能。 
    HSLF- 供读写Microsoft PowerPoint格式档案的功能。 
    HDGF-提供读Microsoft Visio格式档案的功能。 
    HPBF-提供读Microsoft Publisher格式档案的功能。 


二、POI操作Excel 


    1. 官方快速帮助:http://poi.apache.org/spreadsheet/quick-guide.html 

    2. 导入包:poi-3.6.jar 


参考: 



    1. http://www.blogjava.net/vwpolo/archive/2009/09/16/295243.html 

    2. http://hacker-zxf.iteye.com/blog/746546 

    3. http://zmx.iteye.com/blog/622536 

    4. http://canfly2010.iteye.com/blog/701726 
    5. http://blog.csdn.net/aerchi
Java代码  收藏代码
  1. package excel.poi;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.util.Date;  
  8. import java.util.Iterator;  
  9.   
  10. import org.apache.poi.POITextExtractor;  
  11. import org.apache.poi.extractor.ExtractorFactory;  
  12. import org.apache.poi.hssf.usermodel.HSSFCell;  
  13. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  14. import org.apache.poi.hssf.usermodel.HSSFDataFormat;  
  15. import org.apache.poi.hssf.usermodel.HSSFRow;  
  16. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  17. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  18. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;  
  19. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;  
  20. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
  21. import org.apache.poi.ss.usermodel.IndexedColors;  
  22. import org.apache.poi.xssf.usermodel.XSSFCell;  
  23. import org.apache.poi.xssf.usermodel.XSSFCellStyle;  
  24. import org.apache.poi.xssf.usermodel.XSSFCreationHelper;  
  25. import org.apache.poi.xssf.usermodel.XSSFRow;  
  26. import org.apache.poi.xssf.usermodel.XSSFSheet;  
  27. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  28. import org.apache.xmlbeans.XmlException;  
  29. public class ReadExcel {  
  30.     /** 
  31.      * 读取office 2003 xls 
  32.      * @param filePath 
  33.      */  
  34.  @SuppressWarnings({ "unchecked""deprecation" })  
  35. public void loadXls(String filePath){  
  36.       try {  
  37.            InputStream input = new FileInputStream("D:\\aerchi\\test\\xls\\流量.xls");  
  38.            POIFSFileSystem fs = new POIFSFileSystem(input);  
  39.            HSSFWorkbook wb = new HSSFWorkbook(fs);  
  40.            HSSFSheet sheet = wb.getSheetAt(0);  
  41.            // Iterate over each row in the sheet  
  42.            Iterator rows = sheet.rowIterator();  
  43.            while (rows.hasNext()) {  
  44.             HSSFRow row = (HSSFRow) rows.next();  
  45.             System.out.println("Row #" + row.getRowNum());  
  46.             // Iterate over each cell in the row and print out the cell"s  
  47.             // content  
  48.             Iterator cells = row.cellIterator();  
  49.             while (cells.hasNext()) {  
  50.              HSSFCell cell = (HSSFCell) cells.next();  
  51.              System.out.println("Cell #" + cell.getCellNum());  
  52.              switch (cell.getCellType()) {  
  53.              case HSSFCell.CELL_TYPE_NUMERIC:  
  54.               System.out.println(cell.getNumericCellValue());  
  55.               break;  
  56.              case HSSFCell.CELL_TYPE_STRING:  
  57.               System.out.println(cell.getStringCellValue());  
  58.               break;  
  59.              case HSSFCell.CELL_TYPE_BOOLEAN:  
  60.               System.out.println(cell.getBooleanCellValue());  
  61.               break;  
  62.              case HSSFCell.CELL_TYPE_FORMULA:  
  63.               System.out.println(cell.getCellFormula());  
  64.               break;  
  65.              default:  
  66.               System.out.println("unsuported sell type");  
  67.               break;  
  68.              }  
  69.             }  
  70.            }  
  71.           } catch (IOException ex) {  
  72.            ex.printStackTrace();  
  73.           }  
  74.  }  
  75.  /** 
  76.   * 读取xlsx文本 
  77.   * @param filePath 
  78.   */  
  79.  public void loadXlsxText(String filePath){  
  80.      File inputFile = new File("D:\\aerchi.xlsx");     
  81.      try {  
  82.         POITextExtractor extractor = ExtractorFactory.createExtractor(inputFile);  
  83.         System.out.println(extractor.getText());  
  84.     } catch (InvalidFormatException e) {  
  85.         e.printStackTrace();  
  86.     } catch (IOException e) {  
  87.         e.printStackTrace();  
  88.     } catch (OpenXML4JException e) {  
  89.         e.printStackTrace();  
  90.     } catch (XmlException e) {  
  91.         e.printStackTrace();  
  92.     }     
  93.  }  
  94.  /** 
  95.   * 读取office 2007 xlsx 
  96.   * @param filePath 
  97.   */  
  98.  public void loadXlsx(String filePath){  
  99.      // 构造 XSSFWorkbook 对象,strPath 传入文件路径     
  100.     XSSFWorkbook xwb = null;  
  101.     try {  
  102.         xwb = new XSSFWorkbook("D:\\aerchi.xlsx");  
  103.     } catch (IOException e) {  
  104.         System.out.println("读取文件出错");  
  105.         e.printStackTrace();  
  106.     }     
  107.      // 读取第一章表格内容     
  108.      XSSFSheet sheet = xwb.getSheetAt(0);     
  109.     // 定义 row、cell     
  110.      XSSFRow row;     
  111.      String cell;     
  112.      // 循环输出表格中的内容     
  113.      for (int i = sheet.getFirstRowNum()+1; i < sheet.getPhysicalNumberOfRows(); i++) {     
  114.          row = sheet.getRow(i);   
  115.          for (int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++) {     
  116.             // 通过 row.getCell(j).toString() 获取单元格内容,     
  117.              if (j==1&&i!=0) {  
  118.                  cell = row.getCell(j).getDateCellValue().toLocaleString();  
  119.             }else {  
  120.                 cell = row.getCell(j).toString();  
  121.             }  
  122.             /* //获取字体和背景颜色 
  123.             String rgbShort=row.getCell(j).getCellStyle().getFont().getCTFont().getColorArray()[0].xmlText(); 
  124.             rgbShort=ReadExcel.substringBetween(rgbShort, "rgb=\"","\"/>"); 
  125.             String rgbShort=row.getCell(j).getCellStyle().getFillBackgroundXSSFColor().getCTColor().toString(); 
  126.             Color color=new Color(Color.BLUE.getRGB()); 
  127.             System.out.print(cell +",index:"+rgbShort+" red:"+color.getRed()+" blue:"+color.getBlue()+"\t");   */  
  128.             System.out.print(cell +"\t");     
  129.         }     
  130.          System.out.println("");     
  131.      }      
  132.  }  
  133. /** 
  134.  * HSSF 写入excel xls 格式 
  135.  * @param filePath 
  136.  * @throws IOException 
  137.  */  
  138.  public void writeXls(String filePath)throws IOException{  
  139.      //工作簿 23.  
  140.      HSSFWorkbook hssfworkbook=new HSSFWorkbook();   
  141.      //创建sheet页 25.  
  142.      HSSFSheet hssfsheet=hssfworkbook.createSheet();  
  143.      //sheet名称  
  144.      hssfworkbook.setSheetName(0,"研发部门");   
  145.      //取得第一行 29.  
  146.      HSSFRow hssfrow=hssfsheet.createRow(0);   
  147.      //创建第一个单元格并处理乱码 31.  
  148.      HSSFCell hssfcell_0=hssfrow.createCell((short)0);   
  149.      //hssfcell_0.setEncoding(HSSFWorkbook.ENCODING_UTF_16);  
  150.      //对第一个单元格赋值 34.  
  151.      hssfcell_0.setCellValue("研发工程师1");   
  152.      //日期单元格格式处理  
  153.      HSSFCellStyle hssfcellstyle=hssfworkbook.createCellStyle();  
  154.      //m/d/yyh:mm 39.  
  155.      hssfcellstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));   
  156.      //创建第二个单元格 41.  
  157.      HSSFCell hssfcell_1=hssfrow.createCell((short)1);   
  158.      hssfcell_1.setCellValue(new Date());   
  159.      hssfcell_1.setCellStyle(hssfcellstyle);  
  160.      hssfrow.createCell((short)2).setCellValue(true);   
  161.      hssfrow.createCell((short)3).setCellValue(122.00);   
  162.      //输出 49.  
  163.      FileOutputStream fileoutputstream=new FileOutputStream("d:\\exceltext.xls");   
  164.      hssfworkbook.write(fileoutputstream);  
  165.      fileoutputstream.close();  
  166.  }  
  167.  @SuppressWarnings("static-access")  
  168. public void writeXlsx(String filePath)throws IOException{  
  169.      //工作簿  
  170.      XSSFWorkbook hssfworkbook=new XSSFWorkbook();  
  171.     //获得CreationHelper对象,这个应该是一个帮助类     
  172.      XSSFCreationHelper helper=hssfworkbook.getCreationHelper();  
  173.      //创建sheet页  
  174.      XSSFSheet hssfsheet=hssfworkbook.createSheet();  
  175.      //设置sheet名称  
  176.      hssfworkbook.setSheetName(0,"我的测试sheet");   
  177.      //取得第一行   
  178.      XSSFRow firstRow=hssfsheet.createRow(0);   
  179.      //创建第一个单元格  
  180.      XSSFCell hssfcell_0=firstRow.createCell(0);   
  181.      //hssfcell_0.setEncoding(HSSFWorkbook.ENCODING_UTF_16);并处理乱码  
  182.      //对第一个单元格赋值   
  183.      hssfcell_0.setCellValue("名称");   
  184.      //创建第二个单元格   
  185.      XSSFCell hssfcell_1=firstRow.createCell(1);   
  186.      hssfcell_1.setCellValue("创建日期");   
  187.      //日期单元格格式处理  
  188.      XSSFCellStyle dateCellStyle=hssfworkbook.createCellStyle();  
  189.      //m/d/yyh:mm 设置日期格式  
  190.      dateCellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd hh:mm:ss"));   
  191.      dateCellStyle=ReadExcel.setFillBackgroundColors(dateCellStyle, IndexedColors.BLACK.getIndex(), IndexedColors.YELLOW.getIndex(), dateCellStyle.SOLID_FOREGROUND);  
  192.      //设置其他标题  
  193.      firstRow.createCell(2).setCellValue("用户");   
  194.      firstRow.createCell(3).setCellValue("备注");  
  195.        
  196.      //写入所有内容行  
  197.      for (int rowInt = 1; rowInt < 10; rowInt++) {  
  198.         XSSFRow row =hssfsheet.createRow(rowInt);  
  199.         XSSFCell cell_0=row.createCell(0);    
  200.         cell_0.setCellValue("碌人乘凉");  
  201.         XSSFCell cell_1=row.createCell(1);    
  202.         cell_1.setCellValue(new Date());  
  203.         cell_1.setCellStyle(dateCellStyle);  
  204.         XSSFCell cell_2=row.createCell(2);    
  205.         cell_2.setCellValue("超级会员");  
  206.         XSSFCell cell_3=row.createCell(3);    
  207.         cell_3.setCellValue("这里是备注信息");  
  208.           
  209.     }  
  210.      //输出 49.  
  211.      FileOutputStream fileoutputstream=new FileOutputStream("d:\\exceltext.xlsx");   
  212.      hssfworkbook.write(fileoutputstream);  
  213.      fileoutputstream.close();  
  214.  }  
  215.     /**   
  216.      * 前景和背景填充的着色   
  217.      * @param cellStyle   
  218.      * @param bg IndexedColors.ORANGE.getIndex();   
  219.      * @param fg IndexedColors.ORANGE.getIndex();   
  220.      * @param fp CellStyle.SOLID_FOREGROUND   
  221.      * @return   
  222.      */    
  223.     public static XSSFCellStyle setFillBackgroundColors(XSSFCellStyle cellStyle,short bg,short fg,short fp){     
  224.         cellStyle.setFillBackgroundColor(bg);     
  225.         cellStyle.setFillForegroundColor(fg);     
  226.         cellStyle.setFillPattern(fp);     
  227.         return cellStyle;     
  228.     }     
  229.  public static void main(String[] args) {  
  230.      ReadExcel readExcel =new ReadExcel();  
  231.     /*  try { 
  232.             readExcel.writeXlsx(""); 
  233.         } catch (IOException e) { 
  234.             e.printStackTrace(); 
  235.         }*/  
  236.      readExcel.loadXls("");  
  237.  }  
  238.   
  239.    
  240. }