1. 程式人生 > 實用技巧 >java操作Excel簡單入門

java操作Excel簡單入門

簡介

在專案中使用到Excel是很常見的,如批量匯入資料,批量匯出資料。這裡我們使用Apache的開源專案POI來操作Excel。官網

新增依賴

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.9</version>
</dependency>

建立Excel檔案

@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@ToString
@Accessors(chain = true)
public class Person {

  private String username;
  private String gender;
  private String address;
}

定義使用者模型

public class Client {

  public static void main(String[] args) throws Exception {
    List<Person> personList = Arrays.asList(
        new Person().setUsername("李四").setGender("男").setAddress("北京"),
        new Person().setUsername("小王").setGender("女").setAddress("上海"));
    //工作簿 表示一個excel檔案
    Workbook wb = new SXSSFWorkbook();
    //一個表格
    Sheet sheet = wb.createSheet();
    //建立標題行
    Row row = sheet.createRow(0);
    //1個單元格
    Cell cell = row.createCell(0);
    cell.setCellValue("使用者名稱");
    cell = row.createCell(1);
    cell.setCellValue("性別");
    cell = row.createCell(2);
    cell.setCellValue("地址");

    AtomicInteger rowIndex = new AtomicInteger(1);
    for (Person person : personList) {
      //建立資料行
      row = sheet.createRow(rowIndex.getAndIncrement());
      row.createCell(0).setCellValue(person.getUsername());
      row.createCell(1).setCellValue(person.getGender());
      row.createCell(2).setCellValue(person.getAddress());
    }
    wb.write(new FileOutputStream("D:\\person.xlsx"));
  }
}

生成的Excel如下

Workbook在POI中有3種實現,

  • HSSFWorkbook,適用於2003及之前的版本,字尾為.xls,行數最多為65536行
  • XSSFWorkbook,適用於2007及之後的版本,字尾為.xlsx,行數最多為1048576行,可能出現OutOfMemoryError錯誤
  • SXSSFWorkbook,適用於大型Excel檔案的操作,不會造成記憶體溢位,基本原理就是空間換時間,將資料儲存到硬碟中

    可以看到兩種版本的行大小和列大小



    可以看到,在建立行物件之前都會校驗最大行數。
    SXSSFWorkbook會使用很低的記憶體,這是因為超過100行的資料都會儲存到臨時檔案中


    臨時檔案中內容為

讀取Excel檔案

public class Client {

  public static void main(String[] args) throws Exception {

    Workbook wb = new XSSFWorkbook(new FileInputStream("D:\\person.xlsx"));
    Sheet sheet = wb.getSheetAt(0);
    Iterator<Row> rowIterator = sheet.iterator();
    //過濾標題行
    rowIterator.next();
    List<Person> personList = new ArrayList<>();
    while (rowIterator.hasNext()) {
      Row row = rowIterator.next();
      Person person = new Person();
      Cell cell;
      cell = row.getCell(0);
      if (cell != null) {
        person.setUsername(cell.getStringCellValue());
      }
      cell = row.getCell(1);
      if (cell != null) {
        person.setGender(cell.getStringCellValue());
      }
      cell = row.getCell(2);
      if (cell != null) {
        person.setAddress(cell.getStringCellValue());
      }
      personList.add(person);
    }
    System.out.println(personList);
  }

}

可以看到,使用POI操作Excel還是很簡單的,關於更加複雜的Excel功能,請讀者自行研究。