java poi 處理excel表格數據


目的:獲取本地excel表格數據,修改其中的某個值,存入新的excel。

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
            <scope>test</scope>
        </dependency>

 

String filepath = "D:\\software\\t.xlsx";
FileInputStream excelFileInputStream = new FileInputStream(filepath);
XSSFWorkbook workbook = new XSSFWorkbook(excelFileInputStream);//拿到文件轉化為javapoi可操縱類型
excelFileInputStream.close();
XSSFSheet sheet = workbook.getSheetAt(0);
// 獲取行數
int rows = sheet.getLastRowNum();
// 獲取列數
int clos = sheet.getRow(0).getPhysicalNumberOfCells();

XSSFWorkbook work = new XSSFWorkbook();
XSSFSheet she = work.createSheet("tt3");
for (int i = 1; i < rows; i++) {
     XSSFRow row = sheet.getRow(i);//得到行
     // 創建行
     XSSFRow nowRow = she.createRow(i);
     for(int j=0; j<clos; j++){
          XSSFCell cell = row.getCell(j);//得到列
          cell.setCellType(XSSFCell.CELL_TYPE_STRING);
          //System.out.println(cell.getStringCellValue());
          // 創建列
          XSSFCell nowCell = nowRow.createCell(j);
          nowCell.setCellType(XSSFCell.CELL_TYPE_STRING);
          nowCell.setCellValue(cell.getStringCellValue());
      }
      for(int j=0; j<clos; j++){
            XSSFCell cell = nowRow.getCell(j);//得到列
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            System.out.print(cell.getStringCellValue()+" ");
      }
      System.out.println();
}
//保存
FileOutputStream excelFileOutPutStream = new FileOutputStream("D:\\software\\tx.xlsx");//寫數據到這個路徑上
work.write(excelFileOutPutStream);
excelFileOutPutStream.flush();
excelFileOutPutStream.close();
System.out.println("done");

總結:

XSSFWorkbook,HSSFWorkbook每一個對應的版本都不一樣,且對應的導出數據都有限制,詳情參考:https://www.cnblogs.com/skyislimit/articles/10514719.html。

 


免責聲明!

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



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