Apache POI导出excel表格

时间:2023-01-31 17:31:25

项目中我们经常用到导出功能,将数据导出以便于审查和统计等。本文主要使用Apache POI实现导出数据。

POI中文文档

简介

ApachePOI是Apache软件基金会的开放源码函式库,POI提供API给java程序对Microsoft Office格式档案读和写的功能。

HSSF概况

HSSF是Horrible
SpreadSheet
Format的缩写,通过HSSF,你可以用纯java代码来读取、写入、修改Excel文件。HSSF为读取操作提供了两类API:usermodel和eventusermodel,既”用户模型“和”事件-用户模型“。

POI Excel 文档结构类

     HSSFWorkbook excel文档对象
HSSFSheet excel的sheet
HSSFRow excel的行
HSSFCell excel的单元格
HSSFFont excel字体
HSSFName 名称
HSSFDataFormat 日期格式
HSSFHeader sheet头
HSSFFooter sheet尾
HSSFCellStyle cell样式
HSSFDateUtil 日期
HSSFPrintSetup 打印
HSSFErrorConstants 错误信息表
EXCEL常用操作方法

得到Excel常用对象

     POIFSFileSystem fs=newPOIFSFileSystem(new  FileInputStream("d:/test.xls"));
//得到Excel工作簿对象
HSSFWorkbook wb = new HSSFWorkbook(fs);
//得到Excel工作表对象
HSSFSheet sheet = wb.getSheetAt(0);
//得到Excel工作表的行
HSSFRow row = sheet.getRow(i);
//得到Excel工作表指定行的单元格
HSSFCell cell = row.getCell((short) j);
cellStyle = cell.getCellStyle();//得到单元格样式  

建立Excel常用对象

 HSSFWorkbook wb = new HSSFWorkbook();//创建Excel工作簿对象
HSSFSheet sheet = wb.createSheet("new sheet");//创建Excel工作表对象
HSSFRow row = sheet.createRow((short)0); //创建Excel工作表的行
cellStyle = wb.createCellStyle();//创建单元格样式
row.createCell((short)0).setCellStyle(cellStyle); //创建Excel工作表指定行的单元格
row.createCell((short)0).setCellValue(1); //设置Excel工作表的值
设置表格
     //设置sheet名称和单元格内容
wb.setSheetName(1, "第一张工作表",HSSFCell.ENCODING_UTF_16);
cell.setEncoding((short) 1);
cell.setCellValue("单元格内容"); //取得sheet的数目
wb.getNumberOfSheets() //根据index取得sheet对象
HSSFSheet sheet = wb.getSheetAt(0); //取得有效的行数
int rowcount = sheet.getLastRowNum(); //取得一行的有效单元格个数
row.getLastCellNum(); //单元格值类型读写
cell.setCellType(HSSFCell.CELL_TYPE_STRING); //设置单元格为STRING类型
cell.getNumericCellValue();//读取为数值类型的单元格内容 //设置列宽、行高
sheet.setColumnWidth((short)column,(short)width);
row.setHeight((short)height); //添加区域,合并单元格
Region region = new Region((short)rowFrom,(short)columnFrom,(short)rowTo,(short)columnTo);//合并从第rowFrom行columnFrom列
sheet.addMergedRegion(region);// 到rowTo行columnTo的区域
//得到所有区域
sheet.getNumMergedRegions() //保存Excel文件
FileOutputStream fileOut = new FileOutputStream(path);
wb.write(fileOut);

开始实现

pom.xml
     <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poiscratchpad</artifactId>
<version>${poi.version</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poiooxml</artifactId>
<version>${poi.version</version>
</dependency>
excel导出工具类
     public class ExcelExport {
//表头
private String title;
//各个列的表头
private String[] heardList;
//各个列的元素key值
private String[] heardKey;
//需要填充的数据信息
private List<Map> data;
//字体大小
private int fontSize = 14;
//行高
private int rowHeight = 30;
//列宽
private int columWidth = 200;
//工作表
private String sheetName = "sheet1"; public String getTitle() {
return title;
} public ExcelExport setTitle(String title) {
this.title = title;
return this;
} public String[] getHeardList() {
return heardList;
} public ExcelExport setHeardList(String[] heardList) {
this.heardList = heardList;
return this;
} public String[] getHeardKey() {
return heardKey;
} public ExcelExport setHeardKey(String[] heardKey) {
this.heardKey = heardKey;
return this;
} public List<Map> getData() {
return data;
} public ExcelExport setData(List<Map> data) {
this.data = data;
return this;
} public int getFontSize() {
return fontSize;
} public ExcelExport setFontSize(int fontSize) {
this.fontSize = fontSize;
return this;
} public int getRowHeight() {
return rowHeight;
} public ExcelExport setRowHeight(int rowHeight) {
this.rowHeight = rowHeight;
return this;
} public int getColumWidth() {
return columWidth;
} public ExcelExport setColumWidth(int columWidth) {
this.columWidth = columWidth;
return this;
} public String getSheetName() {
return sheetName;
} public ExcelExport setSheetName(String sheetName) {
this.sheetName = sheetName;
return this;
} /**
* 开始导出数据信息
*
* @throws ExcelException 抛出数据异常类
*/
public byte[] exportExport(HttpServletRequest request, HttpServletResponse response) throws ExcelException {
//检查参数配置信息
checkConfig();
//创建工作簿
HSSFWorkbook wb = new HSSFWorkbook();
//创建工作表
HSSFSheet wbSheet = wb.createSheet(this.sheetName);
//在第0行创建rows
HSSFRow row = wbSheet.createRow((int) 0);
//创建单元格,设置表头,表头居中
HSSFCellStyle style = wb.createCellStyle();
//设置单元格样式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short) this.fontSize); //设置列头元素
HSSFCell cellHead = null;
for (int i = 0; i < heardList.length; i++) {
cellHead = row.createCell(i);
cellHead.setCellValue(heardList[i]);
cellHead.setCellStyle(style);
} //开始写入实体数据信息
style.setFont(font);
for (int i = 0; i < data.size(); i++) {
HSSFRow roww = wbSheet.createRow((int) i + 1);
Map map = data.get(i);
HSSFCell cell = null;
for (int j = 0; j < heardKey.length; j++) {
cell = roww.createCell(j);
cell.setCellStyle(style);
Object valueObject = map.get(heardKey[j]);
String value = null;
if (valueObject == null) {
valueObject = "";
}
if (valueObject instanceof String) {
//取出的数据是字符串直接赋值
value = (String) map.get(heardKey[j]);
} else if (valueObject instanceof Integer) {
//取出的数据是Integer
value = String.valueOf(((Integer) (valueObject)).floatValue());
} else if (valueObject instanceof BigDecimal) {
//取出的数据是BigDecimal
value = String.valueOf(((BigDecimal) (valueObject)).floatValue());
} else {
value = valueObject.toString();
}
cell.setCellValue(Strings.isNullOrEmpty(value) ? "" : value);
}
}
//设置行高
//设置行高的过程需要注意的一不包含标题
for (int i = 0; i < data.size() + 1; i++) {
HSSFRow hssfRow = wbSheet.getRow(i);
hssfRow.setHeightInPoints(this.rowHeight);
}
//设置列宽
if (data.size() > 0) {
for (int i = 0; i < data.get(0).size(); i++) {
wbSheet.setColumnWidth(i, MSExcelUtils.pixel2WidthUnits(this.columWidth));
}
} else {
for (int i = 0; i < heardList.length; i++) {
wbSheet.setColumnWidth(i, MSExcelUtils.pixel2WidthUnits(this.columWidth));
}
}
//导出数据
try {
//设置Http响应头告诉浏览器下载这个附件
response.setHeader("Content-Disposition", "attachment;Filename=" + System.currentTimeMillis() + ".xls");
OutputStream outputStream = response.getOutputStream();
wb.write(outputStream);
outputStream.close();
return wb.getBytes();
} catch (Exception ex) {
ex.printStackTrace();
throw new ExcelException("导出Excel出现严重异常,异常信息:" + ex.getMessage());
} } /**
* 检查数据配置问题
*
* @throws ExcelException 抛出数据异常类
*/
protected void checkConfig() throws ExcelException {
if (heardKey == null || heardList.length == 0) {
throw new ExcelException("列名数组不能为空或者为NULL");
} if (fontSize < 0 || rowHeight < 0 || columWidth < 0) {
throw new ExcelException("字体、宽度或者高度不能为负值");
} if (Strings.isNullOrEmpty(sheetName)) {
throw new ExcelException("工作表表名不能为NULL");
}
}
}
Service层
     /**
* 导出分类销售统计
*
* @param request
* @param response
* @param startDate 开始日期
* @param endDate 结束日期
* @param searchKey 关键字
* @param storeId 店铺id
* @param organId 组织id
* @return
*/
public byte[] exportSaleCategory(HttpServletRequest request, HttpServletResponse response, String startDate,String endDate, String searchKey, String storeId, String organId) {
Integer count = augeSaleMapper.countShowCategoryStatistics(storeId, organId, startDate, endDate, searchKey);
List<Map> maps = augeSaleMapper.selectShowCategoryStatistics(storeId, organId, startDate, endDate,searchKey, 0, count);
String[] rowsName = new String[]{"商品分类", "销售数量", "销售金额", "毛利额", "毛利率"};
String[] parames = new String[]{"name", "saleCount", "itemSumPrice", "grossProfit", "grossProfitMargin"};
//创建导出工具类
ExcelExport excelExport = new ExcelExport();
excelExport.setHeardKey(parames).setData(maps).setHeardList(rowsName);
byte[] bytes = excelExport.exportExport(request, response);
return bytes;
}
Controller层
     @RequestMapping(value = "/exportSaleCategory", method = RequestMethod.GET)
public ResponseEntity<byte[]> exportSaleCategory(HttpServletRequest request, HttpServletResponse response, String startDate, String endDate, String searchKey, String storeId) throws Exception {
AugeAdmin admin = (AugeAdmin) session.getAttribute("admin");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String fileName = new String(("品类销售统计.xls").getBytes("UTF-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", fileName);
byte[] bytes = saleService.exportSaleCategory(request, response, Strings.emptyToNull(startDate),
Strings.emptyToNull(endDate), Strings.emptyToNull(searchKey), Strings.emptyToNull(storeId), admin.getOrganId());
return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
}
前端页面
     $("#exportBtn").on('click', function () {
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
var storeId = $("#storeId").val();
var url = "${basePath}/sale/exportSaleCategory?startDate=" + startDate + "&endDate=" +endDate + "&storeId=" + storeId;
window.location.href = url;
});
测试结果

Apache POI导出excel表格