1. 程式人生 > >Java使用Apache POI操作Excel檔案

Java使用Apache POI操作Excel檔案

這裡有一篇非常細緻的文章,可供需要時候檢視 Apache POI使用詳解

1. 新建Maven專案,引入POI的依賴

<!-- apache POI for xls -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>
<!-- apache POI for xlsx -->
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version> </dependency>

2. 匯出Excel(xls)

@Test
public void importExcel() throws IOException {
    //建立新工作簿
    HSSFWorkbook workbook = new HSSFWorkbook();
    //新建工作表
    HSSFSheet sheet = workbook.createSheet("sheet1");
    //建立行,行號作為引數傳遞給createRow()方法,第一行從0開始計算
    HSSFRow row = sheet.createRow(0
); //建立單元格,row已經確定了行號,列號作為引數傳遞給createCell(),第一列從0開始計算 HSSFCell cell = row.createCell(2); //設定單元格的值,即C1的值(第一行,第三列) cell.setCellValue("hello sheet"); //輸出到磁碟中 FileOutputStream fos = new FileOutputStream(new File("D:\\exportTest.xls")); workbook.write(fos); workbook.close(); fos.close(); }

3. 讀取Excel(xls)

@Test
public void importExcel() throws IOException {
    //建立輸入流
    FileInputStream fis = new FileInputStream(new File("D:\\testExcel.xls"));
    //通過建構函式傳參
    HSSFWorkbook workbook = new HSSFWorkbook(fis);
    //獲取工作表
    HSSFSheet sheet = workbook.getSheetAt(0);
    //獲取行,行號作為引數傳遞給getRow方法,第一行從0開始計算
    HSSFRow row = sheet.getRow(0);
    //獲取單元格,row已經確定了行號,列號作為引數傳遞給getCell,第一列從0開始計算
    HSSFCell cell = row.getCell(2);
    //獲取單元格的值,即C1的值(第一行,第三列)
    String cellValue = cell.getStringCellValue();
    System.out.println("第一行第三列的值是"+cellValue);
    workbook.close();
    fis.close();
}

4. 匯出Excel(xlsx)

@Test
public void exportExcel() throws IOException {
    //建立工作簿
    XSSFWorkbook workbook = new XSSFWorkbook();
    //新建工作表
    XSSFSheet sheet = workbook.createSheet("sheet1");
    //建立行,0表示第一行
    XSSFRow row = sheet.createRow(0);
    //建立單元格行號由row確定,列號作為引數傳遞給createCell;第一列從0開始計算
    XSSFCell cell = row.createCell(2);
    //給單元格賦值
    cell.setCellValue("hello sheet in Xlsx");
    //建立輸出流
    FileOutputStream fos = new FileOutputStream(new File("D:\\testExcel.xlsx"));
    workbook.write(fos);
    workbook.close();
    fos.close();
}

5. 讀取Excel(xlsx)

@Test
public void importXlsx() throws IOException {
    //建立輸入流
    FileInputStream fis = new FileInputStream(new File("D:\\testExcel.xlsx"));
    //由輸入流得到工作簿
    XSSFWorkbook workbook = new XSSFWorkbook(fis);
    //得到工作表
    XSSFSheet sheet = workbook.getSheet("sheet1");
    //得到行,0表示第一行
    XSSFRow row = sheet.getRow(0);
    //建立單元格行號由row確定,列號作為引數傳遞給createCell;第一列從0開始計算
    XSSFCell cell = row.getCell(2);
    //給單元格賦值
    String cellValue = cell.getStringCellValue();
    System.out.println("第一行第三列的值是"+cellValue);
    workbook.close();
    fis.close();
}

6. 通用方法處理xls和xlsx

@Test
public void importXlsOrXlsx() throws IOException{
    String filePath = "D://testExcel.xls";
    if(filePath.matches("^.+\\.(?i)((xls)|(xlsx))$"))
    {
        FileInputStream fis = new FileInputStream(filePath);
        boolean is03Excell = filePath.matches("^.+\\.(?i)(xls)$")?true:false;
        Workbook workbook = is03Excell ? new HSSFWorkbook(fis):new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0);
        Row row = sheet.getRow(0);
        Cell cell = row.getCell(2);
        System.out.println("第一行第一列的資料是:"+cell.getStringCellValue());
        workbook.close();
        fis.close();
    }
}

7. 綜合案例

(1) 讀取“user.xls”並儲存於list集合中

user.xls中的資料如下圖所示: 這裡寫圖片描述 userImport.java

package com.fukaiit;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;

public class UserImport {
    public List<User> userImport(String filePath) {
        List<User> userList = new ArrayList<User>();

        try {
            FileInputStream fio = new FileInputStream(filePath);
            HSSFWorkbook workbook = new HSSFWorkbook(fio);
            HSSFSheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                if (row.getRowNum() == 0) {// 首行表頭不讀取
                    continue;
                }

                User user = new User();
                user.setUserName(row.getCell(0).getStringCellValue());
                user.setPassword(row.getCell(1).getStringCellValue());
                user.setAge((int) row.getCell(2).getNumericCellValue());
                user.setAddress(row.getCell(3).getStringCellValue());

                userList.add(user);
            }

            workbook.close();
            fio.close();

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

        return userList;
    }
}

TestUserImport.java

@Test
    public void userImport(){
        List<User> userList = new UserImport().userImport("D://user.xls");
        for (User user : userList) {
            System.out.println("使用者資訊為:"+user.getUserName()+";"+user.getPassword()+";"+user.getAge()+";"+user.getAddress());
        }
    }

執行輸出如下: 這裡寫圖片描述

(2) 將User物件組成的userList匯出到userList.xls檔案中

UserExport.java

package com.fukaiit;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class UserExport {
    public void userExport(String filePath, List<User> userList){
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();

        HSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("使用者名稱");
        titleRow.createCell(1).setCellValue("密碼");
        titleRow.createCell(2).setCellValue("年齡");
        titleRow.createCell(3).setCellValue("地址");

        for (User user : userList) {
            int lastRowNum = sheet.getLastRowNum();//獲取最後一行行號

            HSSFRow row = sheet.createRow(lastRowNum+1);
            row.createCell(0).setCellValue(user.getUserName());
            row.createCell(1).setCellValue(user.getPassword());
            row.createCell(2).setCellValue(user.getAge());
            row.createCell(3).setCellValue(user.getAddress());
        }

        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            workbook.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

TestUserExport.java

@Test
    public void userExport(){
        List<User> userList = new ArrayList<User>();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setUserName("sa"+i);
            user.setPassword("upsd"+i);
            user.setAge(21+i);
            user.setAddress("浙江省");

            userList.add(user);
        }

        new UserExport().userExport("D://userList.xls", userList);
    }

匯出效果如下圖所示: 這裡寫圖片描述

9. 總結

  • 操作excel,Workbook->Sheet->Row->Cell,得到對應物件通常都是get*方法,建立對應物件通常是create*方法
  • 設定sheet名稱
HSSFSheet sheet = workbook.createSheet("測試名稱");

OR

workbook.setSheetName(0, "testname");
  • 設定單元格內容
cell.setCellValue("單元格內容");
  • 獲取sheet數目
workbook.getNumberOfSheets()
  • 根據index取得sheet物件
HSSFSheet sheet = wb.getSheetAt(0);
  • 取得有效的行數
int rowCount = sheet.getLastRowNum();
  • 取得一行的有效單元格個數
row.getLastCellNum();
  • 設定單元格格式
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  • 讀取數值型別的單元格內容
cell.getNumericCellValue();
  • 設定列寬、行高
sheet.setColumnWidth((short)column,(short)width); 
row.setHeight((short)height);
  • 新增區域,合併單元格
CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 3);
sheet.addMergedRegion(cellRangeAddress);
HSSFRow mergedRow = sheet.createRow(0);
HSSFCell mergedCell = mergedRow.createCell(0);
mergedCell.setCellValue("表格標題行");
  • 根據單元格不同屬性返回字串數值
public String getCellStringValue(HSSFCell cell) { 
  String cellValue = ""; 
  switch (cell.getCellType()) { 
    case HSSFCell.CELL_TYPE_STRING://字串型別 
        cellValue = cell.getStringCellValue(); 
        if(cellValue.trim().equals("")||cellValue.trim().length()<=0) 
          cellValue=" "; 
        break; 
    case HSSFCell.CELL_TYPE_NUMERIC: //數值型別 
        cellValue = String.valueOf(cell.getNumericCellValue()); 
        break; 
    case HSSFCell.CELL_TYPE_FORMULA: //公式 
        cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); 
        cellValue = String.valueOf(cell.getNumericCellValue()); 
        break; 
    case HSSFCell.CELL_TYPE_BLANK: 
        cellValue=" "; 
        break; 
    case HSSFCell.CELL_TYPE_BOOLEAN: 
        break; 
    case HSSFCell.CELL_TYPE_ERROR: 
        break; 
    default: 
        break; 
  } 
  return cellValue; 
}
  • 設定樣式
HSSFCellStyle style = wb.createCellStyle(); 
style.set*
  • 設定字型樣式的物件有HSSFCellStyle, HSSFFont, HSSFDataFormat等