①导入相关maven地址②使用单元测试功能进行测试
1. 创建Excel表格
@Test
public void write() throws Exception {
String file = "D:\\info.xlsx";
//创建excel表格
XSSFWorkbook excel = new XSSFWorkbook();
XSSFSheet sheet = excel.createSheet("Sheet1");
//创建行
XSSFRow row = sheet.createRow(0);
//创建单元格,并给单元格赋值
XSSFCell cell1 = row.createCell(0);
cell1.setCellValue("姓名");
XSSFCell cell2 = row.createCell(1);
cell2.setCellValue("年龄");
XSSFCell cell3 = row.createCell(2);
cell3.setCellValue("城市");
//通过输出流,将内存中的excel存入到磁盘中
FileOutputStream out = new FileOutputStream(new File(file));
excel.write(out);
//关闭资源
excel.close();
out.close();
}
创建成功

2. 读取Excel表格
@Test
public void read() throws Exception {
//将磁盘的Excel读取到内存中,使用XSSFWorkbook的有参构造器,传入输入流
FileInputStream in = new FileInputStream(new File("D:\\info.xlsx"));
XSSFWorkbook excel = new XSSFWorkbook(in);
//获取Sheet1标签页的内容
XSSFSheet sheet = excel.getSheet("Sheet1");
//获取有文字的第一行和最后一行
int start = sheet.getFirstRowNum();
int end = sheet.getLastRowNum();
//输出Excel的文字
for(int i = start; i <= end;i++){
XSSFRow row = sheet.getRow(i);
String cell1 = row.getCell(0).getStringCellValue();
String cell2 = row.getCell(1).getStringCellValue();
String cell3 = row.getCell(2).getStringCellValue();
System.out.println(cell1 + " " + cell2 + " " + cell3);
}
//关闭流
in.close();
excel.close();
}
最后输出

总结:一定要写write函数中excel.write(out),不然excel能成功写入磁盘,但是不能正常打开。
注意最后关闭流
2万+

被折叠的 条评论
为什么被折叠?



