Java中POI操作Excel常用方法

一、 POI简介
Apache POIApache软件基金会的开放源码函式库,POI提供APIJava程序对MicrosoftOffice格式档案读和写的功能。

二、 HSSF概况
HSSF HorribleSpreadSheet Format的缩写,通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。HSSF 为读取操作提供了两类APIusermodeleventusermodel,即用户模型事件-用户模型

三、 POI EXCEL文档结构类
HSSFWorkbookexcel文档对象

HSSFSheetexcelsheetHSSFRow excel的行

HSSFCellexcel的单元格 HSSFFontexcel字体

HSSFName 名称HSSFDataFormat 日期格式

HSSFHeadersheet

HSSFFootersheet

HSSFCellStylecell样式

HSSFDateUtil日期

HSSFPrintSetup打印

HSSFErrorConstants错误信息表

四、 EXCEL常用操作方法

1得到Excel常用对象

Java代码

  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();//得到单元格样式
  11. POIFSFileSystem fs=newPOIFSFileSystem(new     FileInputStream("d:/test.xls"));
  12. //得到Excel工作簿对象
  13. HSSFWorkbook wb = new HSSFWorkbook(fs);
  14. //得到Excel工作表对象
  15. HSSFSheet sheet = wb.getSheetAt(0);
  16. //得到Excel工作表的行
  17. HSSFRow row = sheet.getRow(i);
  18. //得到Excel工作表指定行的单元格
  19. HSSFCell cell = row.getCell((short) j);
  20. cellStyle = cell.getCellStyle();//得到单元格样式



2、建立Excel常用对象

Java代码

  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工作表的值    
  7. HSSFWorkbook wb = new HSSFWorkbook();//创建Excel工作簿对象
  8. HSSFSheet sheet = wb.createSheet("new     sheet");//创建Excel工作表对象    
  9. HSSFRow row = sheet.createRow((short)0); //创建Excel工作表的行
  10. cellStyle = wb.createCellStyle();//创建单元格样式
  11. row.createCell((short)0).setCellStyle(cellStyle); //创建Excel工作表指定行的单元格
  12. row.createCell((short)0).setCellValue(1); //设置Excel工作表的值



3、设置sheet名称和单元格内容

Java代码

  1. wb.setSheetName(1, "第一张工作表",HSSFCell.ENCODING_UTF_16);    
  2. cell.setEncoding((short) 1);
  3. cell.setCellValue("单元格内容");
  4. wb.setSheetName(1, "第一张工作表",HSSFCell.ENCODING_UTF_16);    
  5. cell.setEncoding((short) 1);
  6. cell.setCellValue("单元格内容");



4、取得sheet的数目

Java代码

  1. wb.getNumberOfSheets()
  2. wb.getNumberOfSheets()



5根据index取得sheet对象

Java代码

  1. HSSFSheet sheet = wb.getSheetAt(0);
  2. HSSFSheet sheet = wb.getSheetAt(0);



6、取得有效的行数

Java代码

  1. int rowcount = sheet.getLastRowNum();
  2. int rowcount = sheet.getLastRowNum();



7、取得一行的有效单元格个数

Java代码

  1. row.getLastCellNum();
  2. row.getLastCellNum();


8、单元格值类型读写

Java代码

  1. cell.setCellType(HSSFCell.CELL_TYPE_STRING); //设置单元格为STRING类型    
  2. cell.getNumericCellValue();//读取为数值类型的单元格内容
  3. cell.setCellType(HSSFCell.CELL_TYPE_STRING); //设置单元格为STRING类型
  4. cell.getNumericCellValue();//读取为数值类型的单元格内容



9、设置列宽、行高

Java代码

  1. sheet.setColumnWidth((short)column,(short)width);
  2. row.setHeight((short)height);
  3. sheet.setColumnWidth((short)column,(short)width);
  4. row.setHeight((short)height);



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

Java代码

  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()
  6. Region region = new Region((short)rowFrom,(short)columnFrom,(short)rowTo
  7. ,(short)columnTo);//合并从第rowFrom行columnFrom列
  8. sheet.addMergedRegion(region);// 到rowTo行columnTo的区域
  9. //得到所有区域
  10. sheet.getNumMergedRegions()



11、保存Excel文件

Java代码

  1. FileOutputStream fileOut = new FileOutputStream(path);    
  2. wb.write(fileOut);
  3. FileOutputStream fileOut = new     FileOutputStream(path);
  4. wb.write(fileOut);



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

Java代码

  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. }
  28. public String getCellStringValue(HSSFCell cell) {
  29. String cellValue = "";
  30. switch (cell.getCellType()) {
  31. case HSSFCell.CELL_TYPE_STRING://字符串类型
  32. cellValue = cell.getStringCellValue();
  33. if(cellValue.trim().equals("")||cellValue.trim().length()<=0)
  34. cellValue=" ";
  35. break;
  36. case HSSFCell.CELL_TYPE_NUMERIC: //数值类型
  37. cellValue =     String.valueOf(cell.getNumericCellValue());
  38. break;
  39. case HSSFCell.CELL_TYPE_FORMULA: //公式
  40. cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
  41. cellValue =     String.valueOf(cell.getNumericCellValue());
  42. break;
  43. case HSSFCell.CELL_TYPE_BLANK:
  44. cellValue=" ";
  45. break;
  46. case HSSFCell.CELL_TYPE_BOOLEAN:
  47. break;
  48. case HSSFCell.CELL_TYPE_ERROR:
  49. break;
  50. default:
  51. break;
  52. }
  53. return cellValue;
  54. }




13、常用单元格边框格式

Java代码

  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);//上边框
  6. HSSFCellStyle style = wb.createCellStyle();
  7. style.setBorderBottom(HSSFCellStyle.BORDER_DOTTED);//下边框
  8. style.setBorderLeft(HSSFCellStyle.BORDER_DOTTED);//左边框
  9. style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
  10. style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框




14、设置字体和内容位置

Java代码

  1. HSSFFont f = 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);//单元格内容的旋转的角度
  12. HSSFFont f = wb.createFont();
  13. f.setFontHeightInPoints((short) 11);//字号
  14. f.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//加粗
  15. style.setFont(f);
  16. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中
  17. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中
  18. style.setRotation(short rotation);//单元格内容的旋转的角度
  19. HSSFDataFormat df = wb.createDataFormat();
  20. style1.setDataFormat(df.getFormat("0.00%"));//设置单元格数据格式
  21. cell.setCellFormula(string);//给单元格设公式
  22. style.setRotation(short rotation);//单元格内容的旋转的角度




15、插入图片

Java代码

  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));    
  14. //先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
  15. ByteArrayOutputStream byteArrayOut = new     ByteArrayOutputStream();
  16. BufferedImage bufferImg = ImageIO.read(new File("ok.jpg"));
  17. ImageIO.write(bufferImg,"jpg",byteArrayOut);
  18. //读进一个excel模版
  19. FileInputStream fos = new FileInputStream(filePathName+"/stencil.xlt");
  20. fs = new POIFSFileSystem(fos);
  21. //创建一个工作薄
  22. HSSFWorkbook wb = new HSSFWorkbook(fs);
  23. HSSFSheet sheet = wb.getSheetAt(0);
  24. HSSFPatriarch patriarch =     sheet.createDrawingPatriarch();
  25. HSSFClientAnchor anchor = new     HSSFClientAnchor(0,0,1023,255,(short) 0,0,(short)10,10);
  26. patriarch.createPicture(anchor ,     wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));    




16、调整工作表位置

Java代码

  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);
  7. HSSFWorkbook wb = new HSSFWorkbook();
  8. HSSFSheet sheet = wb.createSheet("format     sheet");
  9. HSSFPrintSetup ps = sheet.getPrintSetup();
  10. sheet.setAutobreaks(true);
  11. ps.setFitHeight((short)1);
  12. ps.setFitWidth((short)1);




17、设置打印区域

Java代码

  1. HSSFSheet sheet = wb.createSheet("Sheet1");
  2. wb.setPrintArea(0, "$A$1:$C$2");
  3. HSSFSheet sheet = wb.createSheet("Sheet1");
  4. wb.setPrintArea(0, "$A$1:$C$2");



18、标注脚注

Java代码

  1. HSSFSheet sheet = wb.createSheet("format     sheet");
  2. HSSFFooter footer = sheet.getFooter()
  3. footer.setRight( "Page " +     HSSFFooter.page() + " of " + HSSFFooter.numPages() );
  4. HSSFSheet sheet = wb.createSheet("format     sheet");
  5. HSSFFooter footer = sheet.getFooter()
  6. footer.setRight( "Page " +     HSSFFooter.page() + " of " + HSSFFooter.numPages() );



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

Java代码

  1. HSSFWorkbook wb = new HSSFWorkbook();
  2. HSSFSheet sheet = wb.createSheet("row     sheet");
  3. // Create various cells and rows for spreadsheet.
  4. // Shift rows 6 - 11 on the spreadsheet to the top     (rows 0 - 5)
  5. sheet.shiftRows(5, 10, -5);
  6. HSSFWorkbook wb = new HSSFWorkbook();
  7. HSSFSheet sheet = wb.createSheet("row     sheet");
  8. // Create various cells and rows for spreadsheet.
  9. // Shift rows 6 - 11 on the spreadsheet to the top     (rows 0 - 5)
  10. sheet.shiftRows(5, 10, -5);



20、选中指定的工作表

Java代码

  1. HSSFSheet sheet = wb.createSheet("row     sheet");
  2. heet.setSelected(true);
  3. HSSFSheet sheet = wb.createSheet("row     sheet");
  4. heet.setSelected(true);




21、工作表的放大缩小

Java代码

  1. HSSFSheet sheet1 = wb.createSheet("new     sheet");
  2. sheet1.setZoom(1,2); // 50 percent magnification
  3. HSSFSheet sheet1 = wb.createSheet("new     sheet");
  4. sheet1.setZoom(1,2); // 50 percent magnification




22、头注和脚注

Java代码

  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");
  7. HSSFSheet sheet = wb.createSheet("new     sheet");
  8. HSSFHeader header = sheet.getHeader();
  9. header.setCenter("Center Header");
  10. header.setLeft("Left Header");
  11. header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") +
  12. HSSFHeader.fontSize((short) 16) + "Right w/ Stencil-Normal Italic     font and size 16");



23、自定义颜色

Java代码

  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);
  8. HSSFCellStyle style = wb.createCellStyle();
  9. style.setFillForegroundColor(HSSFColor.LIME.index);
  10. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);    
  11. HSSFFont font = wb.createFont();
  12. font.setColor(HSSFColor.RED.index);
  13. style.setFont(font);
  14. cell.setCellStyle(style);




24、填充和颜色设置

Java代码

  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);
  10. HSSFCellStyle style = wb.createCellStyle();
  11. style.setFillBackgroundColor(HSSFColor.AQUA.index);
  12. style.setFillPattern(HSSFCellStyle.BIG_SPOTS);
  13. HSSFCell cell = row.createCell((short) 1);
  14. cell.setCellValue("X");
  15. style = wb.createCellStyle();
  16. style.setFillForegroundColor(HSSFColor.ORANGE.index);    
  17. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);    
  18. cell.setCellStyle(style);




25、强行刷新单元格公式

Java代码

  1. HSSFFormulaEvaluator eval=new     HSSFFormulaEvaluator((HSSFWorkbook) wb);
  2. privatestaticvoid 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. elseif(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. }
  16. HSSFFormulaEvaluator eval=new     HSSFFormulaEvaluator((HSSFWorkbook) wb);
  17. privatestaticvoid updateFormula(Workbook wb,Sheet s,int row){
  18. Row r=s.getRow(row);
  19. Cell c=null;
  20. FormulaEcaluator eval=null;
  21. if(wb instanceof HSSFWorkbook)
  22. eval=new HSSFFormulaEvaluator((HSSFWorkbook) wb);
  23. elseif(wb instanceof XSSFWorkbook)
  24. eval=new XSSFFormulaEvaluator((XSSFWorkbook) wb);
  25. for(int i=r.getFirstCellNum();i
  26. c=r.getCell(i);
  27. if(c.getCellType()==Cell.CELL_TYPE_FORMULA)
  28. eval.evaluateFormulaCell(c);
  29. }
  30. }




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

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

你可能感兴趣的:(POI,Java)