excel 导入导出
时间: 2023-12-01 10:42:13 浏览: 86
Excel是一种常用的电子表格软件,可以用于数据的存储和处理。在Java中,我们可以使用POI和JXL两种方式来实现Excel的导入导出。其中,POI支持Excel 2007及以上版本,而JXL支持比较低版本的Excel,如Excel 95、97、2000、2003。下面是两种方式的简单实例:
1.使用POI实现Excel导入导出
```java
// 导入Excel
Workbook workbook = WorkbookFactory.create(new FileInputStream("test.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
System.out.print(cell.getStringCellValue() + "\t");
}
System.out.println();
}
// 导出Excel
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello World!");
FileOutputStream outputStream = new FileOutputStream("test.xlsx");
workbook.write(outputStream);
outputStream.close();
```
2.使用JXL实现Excel导入导出
```java
// 导入Excel
Workbook workbook = Workbook.getWorkbook(new File("test.xls"));
Sheet sheet = workbook.getSheet(0);
for (int i = 0; i < sheet.getRows(); i++) {
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j, i);
System.out.print(cell.getContents() + "\t");
}
System.out.println();
}
// 导出Excel
WritableWorkbook workbook = Workbook.createWorkbook(new File("test.xls"));
WritableSheet sheet = workbook.createSheet("Sheet1", 0);
Label label = new Label(0, 0, "Hello World!");
sheet.addCell(label);
workbook.write();
workbook.close();
```
阅读全文