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);

  • 相关阅读:
    bzoj4705: 棋盘游戏
    bzoj4709 [jsoi2011]柠檬
    51nod 1411 矩阵取数问题 V3
    51nod1258 序列求和V4
    51nod 1348 乘积之和
    PostgreSQL Replication之第九章 与pgpool一起工作(3)
    PostgreSQL Replication之第九章 与pgpool一起工作(2)
    PostgreSQL Replication之第九章 与pgpool一起工作(1)
    PostgreSQL Replication之第八章 与pgbouncer一起工作(5)
    PostgreSQL Replication之第八章 与pgbouncer一起工作(4)
  • 原文地址:https://www.cnblogs.com/ae6623/p/4416670.html
Copyright © 2011-2022 走看看