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

由於如今再寫excel2003版的比較low,因此我在這就不介紹了,直接介紹2007,我所用的編程軟件是IDEAweb

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>

 接下來進入正題:apache

一、讀取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());
    }
  }

 

二、從數據庫中取出數據表,導入並生成excelapp

數據庫表名爲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);
    }
  }

三、修改excelspa

//修改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();
    }
  }
相關文章
相關標籤/搜索