POI-入門案例(2/2)

Xiang想`發表於2020-11-29

POI 入門案例

POI 封裝物件:

​ XSSF Workbook :工作簿

​ XSSF Sheel:工作表

​ Row:行

​ Cell:單元格

1、從 Excel 檔案讀取資料

  • 建立工作簿
XSSFWorkbook workbook = new XSSFWorkbook(filePath);
  • 獲取工作表
XSSFSheet sheet = workbook.getSheetAt(0);
  • 遍歷工作表獲得行物件
  • 遍歷物件獲取單元格物件
  • 獲取單元格物件中的值
// 獲取行物件
for (Row row : sheet) {
            // 獲取單元格
            for (Cell cell : row) {
                // 獲取單元格中的內容
                String value = cell.getStringCellValue();
                System.out.println(value);
            }
        }

注意事項,關閉工作流

workbook.close();

除了增強for迴圈可以通過遍歷獲取到值,也可以用普通迴圈獲取

public static void forRead(XSSFSheet sheet){
    // 獲取最後一行
    int lastRowNum = sheet.getLastRowNum();
    for (int i = 0; i <= lastRowNum; i++) {
        XSSFRow row = sheet.getRow(i);
        if (row!=null){
			// 獲取最後一個單元格
            short lastCellNum = row.getLastCellNum();
            for (int j = 0; j <= lastCellNum; j++) {
                XSSFCell cell = row.getCell(j);
                if (cell!=null){
                    String value = cell.getStringCellValue();
                    System.out.println(value);
                }
            }
        }
    }
}

2、向 Excel 檔案寫入資料

  • 建立一個Excel 工作簿
 // 建立工作簿
 XSSFWorkbook workbook = new XSSFWorkbook();
  • 建立工作表
// 建立工作表
XSSFSheet sheet = workbook.createSheet("工作表");
  • 建立行
 // 建立行
XSSFRow row = sheet.createRow(0);
  • 建立單元格賦值
for (int i = 0; i < message.size(); i++) {
    XSSFCell cell = row.createCell(i);
    cell.setCellValue(message.get(i));
}

  • 通過輸出流將物件下載到磁碟
FileOutputStream out = new FileOutputStream(filePath)
// 寫入到 FileOutPutStream 流中
workbook.write(out);
out.flush();

注意事項:

關閉 out 流、關閉 workbook 流

3、程式碼案例

1、讀取

package com.boxuegu.poi;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;

/**
 * @author Xiang想
 * @title: Demo
 * @projectName POITest
 * @description: TODO
 * @date 2020/11/29  1:21
 */
public class Demo {

    public static void main(String[] args) throws IOException {
        String homePath = System.getProperty("user.dir");
        String filePath = File.separator + "src" + File.separator + "main" +
                File.separator + "resources" + File.separator;
        String path =  homePath+filePath+"1.xlsx";
        readExcel(path);
    }

    public static void readExcel(String filePath){
        XSSFWorkbook workbook = null;
        XSSFSheet sheet = null;
        try {
            // 獲取工作簿
            workbook = new XSSFWorkbook(filePath);

            // 獲取工作表
            sheet = workbook.getSheetAt(0);

//            forEachRead(sheet);
            forRead(sheet);



        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (workbook!=null){
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void forEachRead(XSSFSheet sheet){
        // 獲取行
        for (Row row : sheet) {
            // 獲取單元格
            for (Cell cell : row) {
                // 獲取單元格中的內容
                String value = cell.getStringCellValue();
//                    if (value.equals("")){
//                        continue;
//                    }
                System.out.println(value);
            }
        }
    }

    public static void forRead(XSSFSheet sheet){
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 0; i <= lastRowNum; i++) {
            XSSFRow row = sheet.getRow(i);
            if (row!=null){
                short lastCellNum = row.getLastCellNum();
                for (int j = 0; j <= lastCellNum; j++) {
                    XSSFCell cell = row.getCell(j);
                    if (cell!=null){
                        String value = cell.getStringCellValue();
                        System.out.println(value);
                    }
                }
            }
        }
    }
}

2、寫入

package com.boxuegu.poi;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Xiang想
 * @title: Demo2
 * @projectName POITest
 * @description: TODO
 * @date 2020/11/29  2:01
 */
public class Demo2 {
    public static void main(String[] args) {
        String homePath = System.getProperty("user.dir");
        String filePath = File.separator + "src" + File.separator + "main" +
                File.separator + "resources" + File.separator;
        String path =  homePath+filePath+"4.xlsx";
        write(path);

    }

    public static List<String> getMessage(){
        List<String> list = new ArrayList<>();
        list.add("HelloWorld");
        list.add("好好學習,天天向上");
        list.add("我是一個快樂的程式設計師");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        list.add(date);
        return list;
    }


    public static void write(String filePath){

        List<String> message = getMessage();

        // 建立工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 建立工作表
        XSSFSheet sheet = workbook.createSheet("工作表");
        // 建立行
        XSSFRow row = sheet.createRow(0);
        // 建立單元格
        for (int i = 0; i < message.size(); i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(message.get(i));
        }

        // 建立輸出流物件
        try (FileOutputStream out = new FileOutputStream(filePath)) {

            workbook.write(out);
            out.flush();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (workbook!=null){
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

提示:maven座標如下:

<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi</artifactId>
 <version>3.17</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<!-- 支援字尾xlsx -->
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi-ooxml</artifactId>
 <version>3.17</version>
 <exclusions>
     <exclusion>
         <groupId>xml-apis</groupId>
         <artifactId>xml-apis</artifactId>
     </exclusion>
 </exclusions>
</dependency>
好了到這我們的分享也就結束了?
希望以上方法可以幫到您,祝您工作愉快!?
?
對您有幫助的話記點贊得收藏哦!?
我是 Xiang想 從一個小白一步一步地變成工具人 ?