导入依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
导出
代码段:
void poitest1() throws IOException {
//创建工作簿 类似于创建Excel文件
XSSFWorkbook workbook = new XSSFWorkbook();
//创建 sheetname页名
XSSFSheet sheet = workbook.createSheet("员工信息");
sheet.setColumnWidth(3, 20 * 256);//给第3列设置为20个字的宽度
sheet.setColumnWidth(4, 20 * 256);//给第4列设置为20个字的宽度
//创建一行,下标从0开始
XSSFRow row = sheet.createRow(0);
//创建这行中的列,下标从0开始 (表头)
XSSFCell cell = row.createCell(0);
// 给cell 0下表赋值
cell.setCellValue("姓名");
//创建这行中的列,并给该列直接赋值
row.createCell(1).setCellValue("年龄");
row.createCell(2).setCellValue("性别");
row.createCell(3).setCellValue("生日");
row.createCell(4).setCellValue("手机号");
// 设置表里内容
row = sheet.createRow(1);
row.createCell(0).setCellValue("man");
row.createCell(1).setCellValue("保密");
row.createCell(2).setCellValue("男");
row.createCell(3).setCellValue("保密");
row.createCell(4).setCellValue("12121212121");
row = sheet.createRow(2);
row.createCell(0).setCellValue("woman");
row.createCell(1).setCellValue("18");
row.createCell(2).setCellValue("女");
row.createCell(3).setCellValue("2000-01-01");
row.createCell(4).setCellValue("12121212122");
//设定 路径
// Date currenttime=form
// String folder=
File file = new File("C:\\Users\\lyl\\Desktop\\员工信息.xlsx");
FileOutputStream stream = new FileOutputStream(file);
// 需要抛异常
workbook.write(stream);
//关流
stream.close();
}
执行结果:
导入
代码段:
void poitest2() throws IOException {
File file = new File("C:\\Users\\lyl\\Desktop\\员工信息.xlsx");
//获得该文件的输入流
FileInputStream stream = new FileInputStream(file);
// 多态 抛异常
Workbook sheets = new XSSFWorkbook(stream);
//获取一个工作表(sheet页),下标从0开始
Sheet sheet = sheets.getSheetAt(0);
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
// 获取行数
Row row = sheet.getRow(i);
// 获取单元格 取值
String value1 = row.getCell(0).getStringCellValue();
String value2 = row.getCell(1).getStringCellValue();
String value3 = row.getCell(2).getStringCellValue();
String value4 = row.getCell(3).getStringCellValue();
String value5 = row.getCell(4).getStringCellValue();
System.out.println(value1);
System.out.println(value2);
System.out.println(value3);
System.out.println(value4);
System.out.println(value5);
}
//关流
sheets.close();
stream.close();
}
执行结果: