1.介绍
Apache POI是用Java编写的免费开源的跨平台的Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能,其中使用最多的就是使用POI操作Excel文件。
1.1POI的结构
HSSF - 提供读写Microsoft Excel XLS格式档案的功能
XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能
HWPF - 提供读写Microsoft Word DOC格式档案的功能
HSLF - 提供读写Microsoft PowerPoint格式档案的功能
HDGF - 提供读Microsoft Visio格式档案的功能
HPBF - 提供读Microsoft Publisher格式档案的功能
HSMF - 提供读Microsoft Outlook格式档案的功能
2.使用
2.1导入坐标
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi‐ooxml</artifactId>
<version>3.14</version>
</dependency>
2.2读取数据的测试代码
/*
XSSFWorkbook:工作簿
XSSFSheet:工作表
Row:行
Cell:单元格
*/
@Test
public void test1() throws Exception{
List<Entity> entities = new ArrayList<>();
//加载指定文件,创建一个Excel对象(工作簿)
Workbook excel = new XSSFWorkbook(new FileInputStream(new File("d:\\poi.xlsx")));
//读取Excel文件中第一个Sheet标签页
Sheet sheet = excel.getSheetAt(0);
//遍历Sheet标签页,获得每一行数据
int row = 0;
int cell = 0;
for (Row row : sheet) {
cell = 0;
if(row == 0)
continue;
Entity entity = new Entity();
//遍历行,获得每个单元格对象
for (Cell cell : row) {
if(cell == 0){
entity.setName("cell.getStringCellValue()");
System.out.println(cell.getStringCellValue());
}else if(cell == 1){
entity.setAddress("cell.getStringCellValue()");
}else if (cell == 2){
//设置年龄
}
cell++;
}
entities.add(entity);
row++;
}
//关闭资源
excel.close();
}
1.XSSFWorkbook用来读写XLSX格式的文件
2.构造XSSFWorkbook时需要传入inputstream对象
3.getSheetAt(x)可以获取第x+1个Sheet标签页,返回XSSFSheet对象
4. XSSFSheet 实现了 Sheet extends Iterable 接口,所以可以直接进行遍历,获取每一行的数据
5. 遍历Row可以获取每个单元格的数据Cell
@Test
public void test2() throws Exception{
//加载指定文件,创建一个Excel对象(工作簿)
XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File("d:\\poi.xlsx")));
//读取Excel文件中第一个Sheet标签页
XSSFSheet sheet = excel.getSheetAt(0);
//获得当前工作表中最后一个行号,需要注意:行号从0开始
int lastRowNum = sheet.getLastRowNum();
System.out.println("lastRowNum = " + lastRowNum);
for(int i=0;i<=lastRowNum;i++){
XSSFRow row = sheet.getRow(i);//根据行号获取每一行
//获得当前行最后一个单元格索引
short lastCellNum = row.getLastCellNum();
System.out.println("lastCellNum = " + lastCellNum);
for(int j=1;j<=lastCellNum;j++){
XSSFCell cell = row.getCell(j);//根据单元格索引获得单元格对象
System.out.println(cell.getStringCellValue());
}
}
//关闭资源
excel.close();
}
getLastRowNum 返回的最后的行号,比如两行,返回的是1
getLastCellNum 返回的是单元格数量,比如两列,返回的是2
2.3写入数据的测试代码
//使用POI向Excel文件写入数据,并且通过输出流将创建的Excel文件保存到本地磁盘
@Test
public void test3() throws Exception{
//在内存中创建一个Excel文件(工作簿)
XSSFWorkbook excel = new XSSFWorkbook();
//创建一个工作表对象
XSSFSheet sheet = excel.createSheet("传智播客");
//在工作表中创建行对象
XSSFRow title = sheet.createRow(0);
//在行中创建单元格对象
title.createCell(0).setCellValue("姓名");
title.createCell(1).setCellValue("地址");
title.createCell(2).setCellValue("年龄");
XSSFRow dataRow = sheet.createRow(1);
dataRow.createCell(0).setCellValue("小明");
dataRow.createCell(1).setCellValue("北京");
dataRow.createCell(2).setCellValue(20);
//创建一个输出流,通过输出流将内存中的Excel文件写到磁盘
FileOutputStream out = new FileOutputStream(new File("d:\\xieru.xlsx"));
excel.write(out);
out.flush();
excel.close();
}
1.XSSFWorkbook可以直接new创建
2.使用XSSFWorkbook.createSheet创建一个工作表
3.XSSFSheet.createRow创建行,返回XSSFRow对象
4.XSSFRow.createCell(int)创建单元格,直接对单元格setCellValue写入数据
5.创建一个outputstream写入,通过XSSFWorkbook.write写入流
3.POI的工具类
public class POIUtils {
private final static String xls = "xls";
private final static String xlsx = "xlsx";
//格式化时间字符串
private final static String DATE_FORMAT = "yyyy/MM/dd";
/**
* 读入excel文件,解析后返回List(ExcelModel)
* @param file
* @throws IOException
*/
public static List<String[]> readExcel(MultipartFile file) throws IOException {
//检查文件
checkFile(file);
//获得Workbook工作薄对象
Workbook workbook = getWorkBook(file);
//创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
List<String[]> list = new ArrayList<String[]>();
if(workbook != null){
for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
//获得当前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
//获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
//循环除了第一行的所有行
for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
//获得当前行
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
//获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循环当前行
for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
workbook.close();
}
return list;
}
//校验文件是否合法
public static void checkFile(MultipartFile file) throws IOException{
//判断文件是否存在
if(null == file){
throw new FileNotFoundException("文件不存在!");
}
//获得文件名
String fileName = file.getOriginalFilename();
//判断文件是否是excel文件
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
throw new IOException(fileName + "不是excel文件");
}
}
public static Workbook getWorkBook(MultipartFile file) {
//获得文件名
String fileName = file.getOriginalFilename();
//创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream is = file.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if(fileName.endsWith(xls)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
//如果当前单元格内容为日期类型,需要特殊处理
String dataFormatString = cell.getCellStyle().getDataFormatString();
if(dataFormatString.equals("m/d/yy")){
cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
return cellValue;
}
//把数字当成String来读,避免出现1读成1.0的情况
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判断数据的类型
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
}
4.Easypoi
4.1介绍
Easypoi的目标不是替代poi,而是让一个不懂导入导出的快速使用poi完成Excel和word的各种操作,而不是看很多api才可以完成这样工作