1. Apche POI
这里基于apche poi实现,首先需要导入相关依赖。
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
2. Excel 写
注意行号和列号均从0开始。
public static void write() throws IOException {
// 在内存中创建一个Excel文件
XSSFWorkbook excel = new XSSFWorkbook();
// 创建sheet页
XSSFSheet sheet = excel.createSheet("info");
// 创建row对象
XSSFRow row = sheet.createRow(1);
// 创建col并写入文件内容
row.createCell(1).setCellValue("name");
row.createCell(2).setCellValue("city");
row = sheet.createRow(2);
// 创建col并写入文件内容
row.createCell(1).setCellValue("jack");
row.createCell(2).setCellValue("Nan Jing");
// 写入硬盘
FileOutputStream outputStream = new FileOutputStream(new File("info.xlsx"));
excel.write(outputStream);
// 关闭资源
outputStream.close();
excel.close();
}
3. Excel读
public static void read() throws IOException {
FileInputStream inputStream = new FileInputStream(new File("info.xlsx"));
XSSFWorkbook excel = new XSSFWorkbook(inputStream);
XSSFSheet sheet = excel.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for(int i=1; i<=lastRowNum; i++) {
XSSFRow row = sheet.getRow(i);
String string1 = row.getCell(1).getStringCellValue();
String string2 = row.getCell(2).getStringCellValue();
System.out.println(string1 + " " + string2);
}
inputStream.close();
excel.close();
}