1.引入依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
2.读取、写入Excel文件
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;
public class TestOperationExcel {
private static String fileName = "F://demo.xlsx";
public static void main(String[] args) throws Exception{
createExcel();
readExcel();
}
public static void createExcel() throws Exception {
//创建一个excel文件,名称为:
XSSFWorkbook workbook = new XSSFWorkbook();
//创建一个sheet,名称为工作簿1
XSSFSheet sheet = workbook.createSheet("工作簿1");
XSSFRow titleRow = sheet.createRow(0);
XSSFCell nameCell = titleRow.createCell(0);
nameCell.setCellValue("小诸葛的博客");
XSSFCell idCell = titleRow.createCell(1);
idCell.setCellValue("gdupa2015");
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
workbook.write(fileOutputStream);
}
public static void readExcel() throws Exception {
//1.获取excel文件
XSSFWorkbook workbook = new XSSFWorkbook(fileName);
//2.获取第一个工作表
XSSFSheet sheet = workbook.getSheetAt(0);
//3.获取工作表的第一行
XSSFRow row1 = sheet.getRow(0);
//4.获取第一行的第一列、第二列单元格
XSSFCell cell1 = row1.getCell(0);
XSSFCell cell2 = row1.getCell(1);
//5.以字符串方式返回第一列单元格的内容
String cell1Value = cell1.getStringCellValue();
String cell2Value = cell2.getStringCellValue();
System.out.println("name=>" + cell1Value);
System.out.println("id=>" + cell2Value);
}
}