POI是Apache旗下的讀寫微軟Office文檔的開源庫,包括但不限於:Word、Excel、PowerPoint、Visio。官方聲明:從4.0.1版本開始,使用此庫需要jdk1.8或更高的版本支持。本文使用的亦即目前最新的版本是:4.1.2。
本文僅使用了此庫的讀寫excel表格數據的功能,而且是以xlsx爲擴展名的表格文件。
private void onOk() {
String filePath = "E:/setup/test.xlsx";
LinkedList<XSSFRow> list = new LinkedList<XSSFRow>();
try {
// 讀取表格中第一個sheet的數據
readExcel(list, filePath);
// 將上述讀取的數據寫入第二個sheet中
writeExcel(list, filePath);
} catch (Exception x) {
x.printStackTrace();
}
}
private void readExcel(LinkedList<XSSFRow> list, String filePath) throws Exception {
FileInputStream inputStream = new FileInputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheetAt(0); // 獲取表格中第一個sheet
int firstRowNum = sheet.getFirstRowNum(); // 獲取sheet中第一行的序號
int lastRowNum = sheet.getLastRowNum(); // 獲取sheet中最後一行的序號
for (int i = firstRowNum; i <= lastRowNum; i++) {
XSSFRow row = sheet.getRow(i);
if (row == null) {
break;
}
int first = row.getFirstCellNum(); // 獲取當前行中第一個單元格的序號
int last = row.getLastCellNum(); // 獲取當前行中最後一個單元格的序號
if (first < 0 || last < 0) {
break;
}
for (int j = first; j < last; j++) {
XSSFCell cell = row.getCell(j);
CellType cellType = cell.getCellType();
if (cellType == CellType.STRING) {
String value = cell.getStringCellValue();
System.out.println("STRING value=" + value);
} else if (cellType == CellType.NUMERIC) {
String value = cell.getNumericCellValue();
System.out.println("NUMERIC value=" + value);
}
}
list.add(row);
}
inputStream.close();
}
private void writeExcel(LinkedList<XSSFRow> list, String filePath) throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(filePath));
int count = workbook.getNumberOfSheets(); // 獲取表格中sheet的數量
XSSFSheet sheet = null;
if (count > 1) {
sheet = workbook.getSheetAt(1);
} else {
sheet = workbook.createSheet();
}
XSSFRow row;
XSSFCell cell;
//把List裏面的數據寫到excel中
for (int i = 0; i < list.size(); i++) {
// 創建行
row = sheet.createRow(i);
XSSFRow tempRow = list.get(i);
for (int j = tempRow.getFirstCellNum(); j < tempRow.getLastCellNum(); j++) {
cell = row.createCell(j); // 創建單元格
XSSFCell tempCell = tempRow.getCell(j);
switch (tempCell.getCellType()) {
case NUMERIC:
if (DateUtil.isCellDateFormatted(tempCell)) { // 時間格式的單元格,需要特殊處理
Date date = tempCell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
cell.setCellValue(sdf.format(date)); // 設置單元格內容
} else {
cell.setCellValue(tempCell.getNumericCellValue()); // 設置單元格內容
}
break;
case STRING:
cell.setCellValue(tempCell.getStringCellValue()); // 設置單元格內容
break;
}
}
}
//用輸出流寫到excel
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}