POI is an open source library for reading and writing Microsoft Office documents under Apache, including but not limited to: Word, Excel, PowerPoint, Visio. Official statement: Starting from version 4.0.1, using this library requires jdk1.8 or higher version support. The latest version used in this article is: 4.1.2.
This article only uses the function of reading and writing excel table data of this library, and it is a table file with xlsx extension.
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();
}