使用POI库操作excel表

使用POI库操作excel表

最近在Java实习的时候,做的业务很多时候需要读取以及写出excel表,主要是用到了apache的poi库,这里来总结下经验。

POM依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.0</version>
</dependency>

此外还有个库叫poi-excelant是个工具类

如何读取Excel

// 首先获取一个输入流
File file = new File("/Users/xxxxx/Desktop/1.xlsx");
FileInputStream fileInputStream = new FileInputStream(file);

//使用输入流构造XSSFWorkbook对象。
//注意:针对excel的两种格式xls和xlsx,是两种不同的对象,xlsx对应XSSFWorkbook,xls对应HSSFWorkbook
//这里以xlsx为例
XSSFWorkbook sheets = new XSSFWorkbook(stream);
XSSFSheet sheet = sheets.getSheetAt(0); // 可以根据子表的序号或者名字来获取子表对象

XSSFRow headRow = sheet.getRow(0); //读取第一行 可能为null
XSSFCell cell = row.getCell(0); // 读取该行的第一个单元格 可能为null
CellType cellType = cell.getCellType(); // 获取单元格的类型
// 单元格类型分为STRING、BLANK、BOOLEAN、FORMULA、NUMERIC:
// 在excel中日期时间类型是以浮点数的形式存储的。
// 注意日期类型也被分到NUMERIC里面了,区分这两种类型可以使用:
boolean isDate = DateUtil.isCellDateFormatted(cell);
if (isDate) {
    Date dateCellValue = cell.getDateCellValue();
} else {
    Double doubleCellValue = cell.getNumericCellValue();
}

//可以获取最后一行的索引(0开始),但是有的时候表中有空行也会算,所以还是需要检查单元格才行。
int lastRowNum = sheet.getLastRowNum();

如何写入Excel

// 写入的打开方式其实和读取一样,也需要创建XSSFWorkbook实例。
FileOutputStream fileOutputStream = new FileOutputStream("Out.xlsx");
XSSFWorkbook sheets = new XSSFWorkbook(fileOutputStream);
XSSFSheet sheet = sheets.createSheet("第一个sheet");
XSSFRow row = sheet.createRow(0);
XSSCell cell = row.createCell(0);
cell.setCellValue("你好");
XSSCell cell2 = row.createCell(1);
cell2.setCellValue(123.456);
XSSCell cell2 = row.createCell(2);
cell2.setCellValue(true);
XSSCell cell2 = row.createCell(3);
cell2.setCellValue(new Date());

// 合并单元格,合并后的单元格的值等于左上角的单元格的值。
CellRangeAddress cellAddresses = new CellRangeAddress(1, 2 , 1, 2);
sheet.addMergedRegion(cellAddresses);

修改Excel

基本上就是结合上两个方法就行。

使用样式

XSSFCellStyle cellStyle = sheets.createCellStyle(); // 直接new XSSCellStyle是不行的。
XSSFFont xssfFont = sheets.createFont();
xssfFont.setColor(IndexedColors.WHITE.getIndex()); // 设置字体颜色为白色
cellStyle.setFont(xssfFont);

// 设置垂直对齐为顶部
cellStyle.setVerticalAlignment(VerticalAlignment.TOP); 

// 设置边框
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);

// 设置淡绿色背景
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());

// 将样式应用到单元格
XSSFRow row = sheet.createRow(0);
XSSCell cell = row.createCell(0);
cell.setCellValue("你好");
cell.setCellStyle(cellStyle);

//使用非索引颜色, 虽然这里是一个标记弃用的方法,但是默认的索引颜色有时还是满足不了需求。
cellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(216,232,245)));

更多用法可以打开XSSFCellStyle 自行尝试。

posted @ 2020-06-20 18:29  原始锋芒  阅读(723)  评论(0编辑  收藏  举报