1.导入坐标
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
2.写入Excel文件
public class POITest {
public static void write() throws Exception{
XSSFWorkbook excel = new XSSFWorkbook();
XSSFSheet sheet = excel.createSheet("itcast");
XSSFRow row1 = sheet.createRow(0);
row1.createCell(1).setCellValue("姓名");
row1.createCell(2).setCellValue("城市");
XSSFRow row2 = sheet.createRow(1);
row2.createCell(1).setCellValue("张三");
row2.createCell(2).setCellValue("北京");
XSSFRow row3 = sheet.createRow(2);
row3.createCell(1).setCellValue("李四");
row3.createCell(2).setCellValue("上海");
FileOutputStream out = new FileOutputStream(new File("D:\\itcast.xlsx"));
excel.write(out);
out.flush();
out.close();
excel.close();
}
public static void main(String[] args) throws Exception {
write();
}
}
3.读取Excel文件
public class POITest {
public static void read() throws Exception{
FileInputStream in = new FileInputStream(new File("D:\\itcast.xlsx"));
XSSFWorkbook excel = new XSSFWorkbook(in);
XSSFSheet sheet = excel.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= lastRowNum; i++) {
XSSFRow titleRow = sheet.getRow(i);
XSSFCell cell1 = titleRow.getCell(1);
String cellValue1 = cell1.getStringCellValue();
XSSFCell cell2 = titleRow.getCell(2);
String cellValue2 = cell2.getStringCellValue();
System.out.println(cellValue1 + " " +cellValue2);
}
in.close();
excel.close();
}
public static void main(String[] args) throws Exception {
read();
}
}