1 背景介绍
当需要批量操作数据时, 通常做法是下载一个Excel模板, 填写好相关数据后提交, 由后台对模板中的数据进行批量的"增, 删, 改"操作
那么后台如何操作Excel文件呢? 于是今天的主角Apache POI登场了
2 具体操作
2.1 导入jar包
<!--Apache POI,XSSF对象,操作.xlsx-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2.2 获取待操作对象
2.2.1 操作已有的Excel文件,获取XSSFSheet,XSSFRow,XSSFCell对象
// 读取已有的.xlsx文件,生成WorkBook对象,用该对象操作Excel文件
fis = new FileInputStream("D:\\aaa\\poiStudy.xlsx");
workbook = new XSSFWorkbook(fis);
// 读取对应的sheet页
XSSFSheet sheet = workbook.getSheet("sheet");
// 读取sheet页中的"行对象row"
XSSFRow row = sheet.getRow(0);
// 读取行中的"单元格对象cell"
XSSFCell cell = row.getCell(0);
2.2.2 创建新的Excel文件,生成XSSFSheet,XSSFRow,XSSFCell对象
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet");
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
2.3 常用设置
// 设置第1列单元格列宽,默认1/256字符宽度
sheet.setColumnWidth(0, 3 * 256);
// XSSFCellStyle设置单元格样式
XSSFCellStyle cellStyle = workbook.createCellStyle();
// 设置单元格边框
cellStyle.setBorderTop(BorderStyle.THIN); // 上边框
cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
cellStyle.setBorderLeft(BorderStyle.THIN); // 左边框
cellStyle.setBorderRight(BorderStyle.THIN); // 右边框
// 背景色填充(3表示绿色背景)
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 设定填充单色
cellStyle.setFillForegroundColor((short)3); // 设置背景颜色
// 设置字体
cellStyle.setAlignment(HorizontalAlignment.CENTER); // 设置水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 设置垂直居中
XSSFFont font = workbook.createFont();
font.setColor((short)2); // 2代表红色字体
font.setBold(true); // 字体加粗
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
cell.setCellValue("POI学习"); // 单元格实际内容
2.4 文件打印
File file = null;
FileOutputStream fos = null;
OutputStream os = null;
try {
file = new File("D:\\aaa\\poiStudy.xlsx");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
fos = new FileOutputStream(file);
// 打印到本地磁盘
workbook.write(fos);
// 打印到response
os = response.getOutputStream();
workbook.write(os);
} catch (Exception e) {
throw e;
} finally {
IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(workbook);
}
(文件效果展示)