java读写excel文件xlsx
时间: 2023-08-19 08:05:43 浏览: 102
Java读写Excel文件可以使用Apache POI库,下面是一个简单的读写Excel文件的示例代码:
1. 读取Excel文件
```
public static void readExcelFile(String filePath) {
try {
FileInputStream file = new FileInputStream(new File(filePath));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
}
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
```
2. 写入Excel文件
```
public static void writeExcelFile(String filePath) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
Object[][] data = {
{"Name", "Age", "Gender"},
{"Tom", 20, "Male"},
{"Lucy", 18, "Female"},
{"Jack", 22, "Male"},
{"Lily", 21, "Female"}
};
int rowNum = 0;
for (Object[] rowData : data) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (Object field : rowData) {
Cell cell = row.createCell(colNum++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try {
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
```
注意:在使用POI库之前,需要先引入相关的依赖。
阅读全文