用java 写一个加载excel文件,写入三行数据,再输出excel的方法
时间: 2024-02-25 22:57:48 浏览: 22
好的,可以使用Java中的Apache POI库来实现加载excel文件,写入数据和输出excel文件的操作。以下是示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelHandler {
public static void main(String[] args) {
try {
// 读取excel文件
FileInputStream file = new FileInputStream(new File("example.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
// 写入三行数据
Row row1 = sheet.createRow(sheet.getLastRowNum() + 1);
Cell cell1 = row1.createCell(0);
cell1.setCellValue("data1");
Cell cell2 = row1.createCell(1);
cell2.setCellValue(1);
Cell cell3 = row1.createCell(2);
cell3.setCellValue(10);
Row row2 = sheet.createRow(sheet.getLastRowNum() + 1);
Cell cell4 = row2.createCell(0);
cell4.setCellValue("data2");
Cell cell5 = row2.createCell(1);
cell5.setCellValue(2);
Cell cell6 = row2.createCell(2);
cell6.setCellValue(20);
Row row3 = sheet.createRow(sheet.getLastRowNum() + 1);
Cell cell7 = row3.createCell(0);
cell7.setCellValue("data3");
Cell cell8 = row3.createCell(1);
cell8.setCellValue(3);
Cell cell9 = row3.createCell(2);
cell9.setCellValue(30);
// 输出excel文件
FileOutputStream outputFile = new FileOutputStream(new File("output.xlsx"));
workbook.write(outputFile);
outputFile.close();
System.out.println("Excel file has been written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们首先使用`FileInputStream`和`XSSFWorkbook`类来读取名为example.xlsx的excel文件,并获取第一个工作表的引用。接下来,我们使用`createRow`和`createCell`方法创建三个行和九个单元格,并使用`setCellValue`方法写入数据。最后,我们使用`FileOutputStream`类将修改后的工作簿对象输出为名为output.xlsx的excel文件。