编写程序实现JAVA创建EXCEL文件、向EXCEL中输入数据、从EXCEL中读取数据等操作
时间: 2024-04-30 07:25:13 浏览: 136
1. 创建Excel文件:
```java
public class CreateExcel {
public static void main(String[] args) throws IOException {
//创建工作簿
Workbook workbook = new XSSFWorkbook();
//创建sheet
Sheet sheet = workbook.createSheet("sheet1");
//创建行
Row row = sheet.createRow(0);
//创建单元格
Cell cell = row.createCell(0);
//设置单元格的值
cell.setCellValue("Hello World!");
//输出Excel文件
FileOutputStream outputStream = new FileOutputStream("test.xlsx");
workbook.write(outputStream);
outputStream.close();
System.out.println("Excel文件创建成功!");
}
}
```
2. 向Excel中写入数据:
```java
public class WriteExcel {
public static void main(String[] args) throws IOException {
//读取已有的Excel文件
FileInputStream inputStream = new FileInputStream("test.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream);
//获取sheet
Sheet sheet = workbook.getSheet("sheet1");
//创建行
Row row = sheet.createRow(1);
//创建单元格
Cell cell = row.createCell(0);
//设置单元格的值
cell.setCellValue("Java");
//输出Excel文件
FileOutputStream outputStream = new FileOutputStream("test.xlsx");
workbook.write(outputStream);
outputStream.close();
System.out.println("Excel文件写入成功!");
}
}
```
3. 从Excel中读取数据:
```java
public class ReadExcel {
public static void main(String[] args) throws IOException {
//读取已有的Excel文件
FileInputStream inputStream = new FileInputStream("test.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream);
//获取sheet
Sheet sheet = workbook.getSheet("sheet1");
//获取行数和列数
int rowNum = sheet.getLastRowNum();
int colNum = sheet.getRow(0).getLastCellNum();
//读取数据
for (int i = 0; i <= rowNum; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < colNum; j++) {
Cell cell = row.getCell(j);
System.out.print(cell.toString() + "\t");
}
System.out.println();
}
inputStream.close();
System.out.println("Excel文件读取成功!");
}
}
```
阅读全文