在Java中,可以使用Apache POI库来读写Excel文件。以下是一个简单的示例代码,演示如何读取和写入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(); } } }
- 写入Excel文件:
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(); } } }
以上是一个简单的示例,你可以根据自己的需求修改代码以满足具体的需求。希望对你有帮助。