用java实现一个方法: 往xlsx文件写入内容
时间: 2023-05-23 07:04:53 浏览: 73
A:
以下是用Java实现往xlsx文件写入内容的示例代码:
```
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WriteExcel {
public static void main(String[] args) {
try {
// 创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建表格
Sheet sheet = workbook.createSheet();
// 创建第一行,并设置值
Row row1 = sheet.createRow(0);
Cell cell11 = row1.createCell(0);
cell11.setCellValue("姓名");
Cell cell12 = row1.createCell(1);
cell12.setCellValue("年龄");
// 创建第二行,并设置值
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("张三");
Cell cell22 = row2.createCell(1);
cell22.setCellValue(20);
// 创建第三行,并设置值
Row row3 = sheet.createRow(2);
Cell cell31 = row3.createCell(0);
cell31.setCellValue("李四");
Cell cell32 = row3.createCell(1);
cell32.setCellValue(25);
// 将工作簿写入文件
FileOutputStream fos = new FileOutputStream("test.xlsx");
workbook.write(fos);
fos.close();
System.out.println("写入成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
首先,需要导入Apache POI库,该库是用于操作Microsoft Office格式文件的开源Java库。
在代码中,我们首先创建了一个XSSFWorkbook对象,在该对象上创建一个Sheet对象,表示要操作的表格。
接着,我们创建了第一行和第二行,并在单元格中设置了值“姓名”和“年龄”、“张三”和“20”。
最后,我们将工作簿写入到文件中,并在控制台输出写入成功的提示。
以上代码可以在Java SE 1.7及以上版本中运行,需要注意的是必须导入Apache POI的相关库。