需要的包
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
方法 ↓ ↓ ↓
相当于表头
//相当于创建一个excel表格
XSSFWorkbook workbook = new XSSFWorkbook();
//相当于创建一个sheet(一页)
XSSFSheet sheet = workbook.createSheet();
//创建一行
XSSFRow row = sheet.createRow(0);
//创建列(单元格) 第一行第一列
XSSFCell cell = row.createCell(0);
//给第一行第一列第一个单元格赋值
cell.setCellValue("名称");
//创建列(单元格) 第一行第二列
XSSFCell cell1 = row.createCell(1);
//给第一行第二列第一个单元格赋值
cell1.setCellValue("年龄");
//创建列(单元格) 第一行第三列
XSSFCell cell2 = row.createCell(2);
//给第一行第三列第一个单元格赋值
cell2.setCellValue("性别");
相当于表格内容
//创建一行
row = sheet.createRow(1);
//创建列(单元格) 第二行第一列
cell = row.createCell(0);
//给第二行第一列第一个单元格赋值
cell.setCellValue("JAVA");
//创建列(单元格) 第二行第二列
cell1 = row.createCell(1);
//给第二行第二列第一个单元格赋值
cell1.setCellValue("58");
//创建列(单元格) 第二行第三列
cell2 = row.createCell(2);
//给第二行第三列第一个单元格赋值
cell2.setCellValue("女");
IO流
//IO流
OutputStream outputStream =null;
try {
//创建表格文档路径
outputStream = new FileOutputStream("D:\\demo1.xlsx");
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
//关闭IO流
if (outputStream != null){
outputStream.close();
}
if (workbook != null){
workbook = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
最终结果展示