在Java中,可以使用Apache POI庫來讀寫Excel文件。以下是一個簡單的示例代碼,演示如何讀取和寫入Excel文件:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadExcelFile {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("example.xlsx");
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
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.print(" \t");
}
}
System.out.println();
}
workbook.close();
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteExcelFile {
public static void main(String[] args) {
try {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello");
FileOutputStream fileOut = new FileOutputStream("output.xlsx");
workbook.write(fileOut);
workbook.close();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上是一個簡單的示例,你可以根據自己的需求修改代碼以滿足具體的需求。希望對你有幫助。