zoukankan      html  css  js  c++  java
  • java操作Excel(org.apache.poi.hssf.usermodel)

       try{

              POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("c:/a.xls"));

              HSSFWorkbook wb = new HSSFWorkbook(fs);

              HSSFSheet sheet = wb.getSheetAt(0);

              HSSFRow row = sheet.getRow(0);

              // 这个判断很必要  确保下面cell操作顺利执行

              if(row == null){

                  row = sheet.createRow(0);

              }

              HSSFCell cell = row.getCell(1, Row.RETURN_NULL_AND_BLANK);

              if(cell == null){

                  cell = row.createCell(1,HSSFCell.CELL_TYPE_STRING);

                  cell.setCellValue("hahaha");

                  // 保存修改

                  FileOutputStream fileOut = new FileOutputStream("c:/a.xls");

                  wb.write(fileOut);

                  fileOut.close();

              }else{

                  System.out.println(cell.getStringCellValue());

              }

           }catch(Exception e){

              e.printStackTrace();

           }

    // 获取指定cell的值  如:G5
    CellReference ref = new CellReference("G5");
    HSSFCell cell = sheet.getRow(ref.getRow()).getCell(ref.getCol());
    System.out.println(cell.getStringCellValue());

    // 设置指定cell的值 如:G5
    CellReference ref = new CellReference(“G5”);
    sheet.getRow(ref.getRow()).getCell(ref.getCol()).setCellValue("haha");

    // 单元格合并  from:A1  to:F10
    CellReference rFrom = new CellReference(from);
    CellReference rTo = new CellReference(to);
    sheet.addMergedRegion(new CellRangeAddress(rFrom.getRow(),rTo.getRow(),rFrom.getCol(),rTo.getCol()));
    // 设置cell为日期格式
    HSSFDataFormat format = this.wb.createDataFormat();
    style.setDataFormat(format.getFormat(“m月d日”));
    row.createCell(i).setCellStyle(style);

    // 单元格是否加锁
    HSSFCellStyle style = wb.createCellStyle();
    style.setLocked(false);  // true加  false不加

    // 设置货币型(3位一逗号)

    HSSFDataFormat format = wb.createDataFormat();

    HSSFCellStyle style = wb.createCellStyle();

    style.setDataFormat(format.getFormat("#,##0"));

    cell.setCellStyle(style);

    cell.setCellValue(888888988);

    // 出力excel时,模板里有现成的sum公式,但出力后不自动计算的解决办法

    getWorkBook().getSheetAt(OUTPUT_SHEET_INDEX).setForceFormulaRecalculation(true);

  • 相关阅读:
    ZOJ 2158 Truck History
    Knight Moves (zoj 1091 poj2243)BFS
    poj 1270 Following Orders
    poj 2935 Basic Wall Maze (BFS)
    Holedox Moving (zoj 1361 poj 1324)bfs
    ZOJ 1083 Frame Stacking
    zoj 2193 Window Pains
    hdu1412{A} + {B}
    hdu2031进制转换
    openjudge最长单词
  • 原文地址:https://www.cnblogs.com/ae6623/p/4416670.html
Copyright © 2011-2022 走看看