poi操作excel2007(讀取、生成、編輯)


因為現在再寫excel2003版的比較low,所以我在這就不介紹了,直接介紹2007,我所用的編程軟件是IDEA

poi操作office總共有6個jar包,在pom.xml文件中配置如下,也可下載后直接引jar包(快捷鍵ctrl+shift+alt+s----->modules,添加jar包即可)目前poi的jar包最高版本為3.1.6

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-examples</artifactId>
    <version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-excelant</artifactId>
    <version>3.16</version>
</dependency>

 接下來進入正題:

1、讀取excel

//讀取excel表格中的數據,path代表excel路徑
  public void readExecl(String path) {
    try {
      //讀取的時候可以使用流,也可以直接使用文件名
      XSSFWorkbook xwb = new XSSFWorkbook(path);
      //循環工作表sheet
      for (int numSheet = 0; numSheet < xwb.getNumberOfSheets(); numSheet++) {
        XSSFSheet xSheet = xwb.getSheetAt(numSheet);
        if (xSheet == null) {
          continue;
        }
        //循環行row
        for (int numRow = 0; numRow <= xSheet.getLastRowNum(); numRow++) {
          XSSFRow xRow = xSheet.getRow(numRow);
          if (xRow == null) {
            continue;
          }
          //循環列cell
          for (int numCell = 0; numCell <= xRow.getLastCellNum(); numCell++) {
            XSSFCell xCell = xRow.getCell(numCell);
            if (xCell == null) {
              continue;
            }
            //輸出值
            System.out.println("excel表格中取出的數據" + getValue(xCell));
          }
        }

      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 取出每列的值
   *
   * @param xCell 列
   * @return
   */
  private String getValue(XSSFCell xCell) {
    if (xCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
      return String.valueOf(xCell.getBooleanCellValue());
    } else if (xCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
      return String.valueOf(xCell.getNumericCellValue());
    } else {
      return String.valueOf(xCell.getStringCellValue());
    }
  }

 

2、從數據庫中取出數據表,導入並生成excel

數據庫表名為Vt_User,其他注釋都寫得很清楚

public void createExcel() {
    try {
      String path = "D:/test.xlsx";
      // 創建新的Excel 工作簿
      XSSFWorkbook workbook = new XSSFWorkbook();
      // 在Excel工作簿中建一工作表,其名為缺省值
      // 如要新建一名為"用戶表"的工作表,其語句為:
      XSSFSheet sheet = workbook.createSheet("用戶表");
      // 在索引0的位置創建行(最頂端的行)
      XSSFRow row = sheet.createRow((short) 0);
      //在索引0的位置創建單元格(左上端)
      XSSFCell cell = row.createCell((short) 0);
      //創建單元格樣式
      CellStyle cellStyle = workbook.createCellStyle();
      // 設置這些樣式
      cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
      cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
      cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
      cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
      cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
      cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
      cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

      // 定義單元格為字符串類型
      cell.setCellType(HSSFCell.CELL_TYPE_STRING);
      // 在單元格中輸入一些內容
      cell = row.createCell((short) 0);
      cell.setCellValue("用戶id");
      cell.setCellStyle(cellStyle);

      cell = row.createCell((short) 1);
      cell.setCellValue("姓名");
      cell.setCellStyle(cellStyle);

      cell = row.createCell((short) 2);
      cell.setCellValue("別名");
      cell.setCellStyle(cellStyle);

      cell = row.createCell((short) 3);
      cell.setCellValue("密碼");
      cell.setCellStyle(cellStyle);

      cell = row.createCell((short) 4);
      cell.setCellValue("外來id");
      cell.setCellStyle(cellStyle);

      //查詢數據庫中所有的數據
      VtUserMapper mapper = getMapper(VtUserMapper.class);
      VtUserCriteria cri = new VtUserCriteria();
      cri.createCriteria().andUserEnabledEqualTo(1);
      List<VtUser> list = mapper.selectByExample(cri);
      /*//第一個sheet第一行為標題
      XSSFRow rowFirst = sheet.createRow(0);
      rowFirst.setHeightInPoints(21.75f);*/
      for (int i = 0; i < list.size(); i++) {
        row = sheet.createRow((int) i + 1);
        VtUser stu = (VtUser) list.get(i);
        // 第四步,創建單元格,並設置值
        row.createCell((short) 0).setCellValue(stu.getUserId());
        row.createCell((short) 1).setCellValue(stu.getUserName());
        row.createCell((short) 2).setCellValue(stu.getUserNameZn());
        row.createCell((short) 3).setCellValue(stu.getUserPassword());
        row.createCell((short) 4).setCellValue(stu.getUserForeignId());
        sheet.autoSizeColumn((short) 0); //調整第一列寬度(自適應),只識別數字、字母
        sheet.autoSizeColumn((short) 1); //調整第二列寬度
        //調整第三列寬度,有中文,先判斷這一列的最長字符串
        int length = stu.getUserNameZn().getBytes().length;
        sheet.setColumnWidth((short)2,(short)(length*2*256));
        sheet.autoSizeColumn((short) 3); //調整第四列寬度
        sheet.autoSizeColumn((short) 4); //調整第五列寬度

        /*Font font = workbook.createFont();
        font.setFontHeightInPoints((short)18); //字體大小
        sheet.setDefaultRowHeightInPoints(21.75f);
        font.setFontName("楷體");
        font.setBoldweight(Font.BOLDWEIGHT_BOLD); //粗體
        font.setColor(HSSFColor.GREEN.index);    //綠字- 字體顏色*/
      }
      // 新建一輸出文件流
      FileOutputStream fOut = new FileOutputStream(path);
      // 把相應的Excel 工作簿存盤
      workbook.write(fOut);
      //清空緩沖區數據
      fOut.flush();
      // 操作結束,關閉文件
      fOut.close();
      System.out.println("文件生成...");
    } catch (Exception e) {
      System.out.println("已運行 xlCreate() : " + e);
    }
  }

3、修改excel

//修改excel表格,path為excel修改前路徑(D:\\test.xlsx)
  public void writeExcel3(String path) {
    try {
      //傳入的文件
      FileInputStream fileInput = new FileInputStream(path);
      //poi包下的類讀取excel文件

      // 創建一個webbook,對應一個Excel文件
      XSSFWorkbook workbook = new XSSFWorkbook(fileInput);
      //對應Excel文件中的sheet,0代表第一個
      XSSFSheet sh = workbook.getSheetAt(0);
      //修改excle表的第5行,從第三列開始的數據
      for (int i = 2; i < 4; i++) {
        //對第五行的數據修改
        sh.getRow(4).getCell((short) i).setCellValue(100210 + i);
      }
      //將修改后的文件寫出到D:\\excel目錄下
      FileOutputStream os = new FileOutputStream("D:\\修改后test.xlsx");
      // FileOutputStream os = new FileOutputStream("D:\\test.xlsx");//此路徑也可寫修改前的路徑,相當於在原來excel文檔上修改
      os.flush();
      //將Excel寫出
      workbook.write(os);
      //關閉流
      fileInput.close();
      os.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM