Java使用HSSFWorkbook生成Excel
HSSF 是Horrible SpreadSheet Format的缩写,也即“讨厌的电子表格格式”。 也许HSSF的名字有点滑稽,就本质而言它是一个非常严肃、正规的API。通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。
1 创建对象
HSSFWorkbook workbook = new HSSFWorkbook();
2 样式
2.1 基础样式
//创建样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
//水平居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
//垂直居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//自动换行
cellStyle.setWrapText(true);
//设置字体
HSSFFont cellFont = workbook.createFont();
cellFont.setFontName("宋体");
cellStyle.setFont(cellFont);
2.2 背景颜色
//创建背景颜色颜色样式
HSSFCellStyle colorStyle = workbook.createCellStyle();
colorStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//随便设置一个颜色
colorStyle.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());
//自定义填充颜色 替换刚刚设置的颜色
HSSFPalette customPalette = workbook.getCustomPalette();
customPalette.setColorAtIndex(IndexedColors.LIGHT_TURQUOISE.getIndex(), (byte) 255,(byte) 244, (byte) 144);
colorStyle.setAlignment(HorizontalAlignment.CENTER);
colorStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//设置背景会去除边框,因此需要重新添加
colorStyle.setBorderBottom(BorderStyle.THIN);
colorStyle.setBorderLeft(BorderStyle.THIN);
colorStyle.setBorderTop(BorderStyle.THIN);
colorStyle.setBorderRight(BorderStyle.THIN);
//设置边框颜色
colorStyle.setBottomBorderColor(IndexedColors.CORAL.getIndex());
colorStyle.setTopBorderColor(IndexedColors.CORAL.getIndex());
colorStyle.setLeftBorderColor(IndexedColors.CORAL.getIndex());
colorStyle.setRightBorderColor(IndexedColors.CORAL.getIndex());
//创建边框颜色,灰色
HSSFPalette customPalette2 = workbook.getCustomPalette();
customPalette2.setColorAtIndex(IndexedColors.CORAL.getIndex(), (byte) 208,(byte) 214, (byte) 228);
//ps:如果需要设置合并单元格(在下面介绍)的背景颜色,请先创建好单独的单元格并设置背景,最后进行合并操作,否则无法设置背景颜色
2.3 文字颜色样式
HSSFCellStyle redFont = workbook.createCellStyle();
//设置居中
redFont.setVerticalAlignment(VerticalAlignment.CENTER);
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)12);
//设置字体
font.setFontName("宋体");
//加粗
font.setBold(true);
font.setColor(Font.COLOR_RED);
redFont.setFont(font);
redFont.setFillBackgroundColor(Font.COLOR_NORMAL);
redFont.setFont(font);
redFont.setWrapText(true);
3 创建单元格并输入数据
//创建个空白的sheet,设置默认的列宽行高
HSSFSheet sheet = workbook.createSheet("我是sheet名");
sheet.setDefaultColumnWidth((short)16);
sheet.setDefaultRowHeight((short)450);
//创建第一行
HSSFRow row = sheet.createRow(0);
//可以单独设置改行的高度
row.setHeightInPoints(52);
//设置excel内容
//合并表格,起始行,结束行,起始列,结束列
sheet.addMergedRegion(new CellRangeAddress(0,0,0,7));
//创建标题,创建第一格,因为合并了,直接装填第一格即可
HSSFCell cell = row.createCell(0);
cell.setCellValue("我是标题");
cell.setCellStyle(cellStyle);
//创建新行,设置每个单元格内容
row = sheet.createRow(1);
//获取第0格
cell = row.createCell(0);
//设置内容
cell.setCellValue("单元格1");
//设置单元格格式
cell.setCellStyle(cellStyle);
cell = row.createCell(1);
cell.setCellValue("单元格2");
cell.setCellStyle(cellStyle);
cell = row.createCell(2);
cell.setCellValue("单元格3");
cell.setCellStyle(cellStyle);
//冻结单元格,要冻结的列数,要冻结的行数,可以冻结表头,方便用户观看
sheet.createFreezePane(0,2);
//ps:在excel中换行符为\r\n,可创建多行内容
4 为单元格设置下拉框
DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
//下拉框的范围,起始行,结束行,起始列,结束列
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(3,400,3,3);
//设置选项内容
DataValidationConstraint explicitListConstraint = dataValidationHelper.createExplicitListConstraint(new String[]{"重要","普通"});
//装填
DataValidation validation = dataValidationHelper.createValidation(explicitListConstraint, cellRangeAddressList);
sheet.addValidationData(validation);
CellRangeAddressList cellRangeAddressList2 = new CellRangeAddressList(3,400,4,4);
DataValidationConstraint explicitListConstraint2 = dataValidationHelper.createExplicitListConstraint(new String[]{"111","222","333"});
DataValidation validation2 = dataValidationHelper.createValidation(explicitListConstraint2, cellRangeAddressList2);
sheet.addValidationData(validation2);
5 为单元格设置时间格式
HSSFCellStyle dateStyle = workbook.createCellStyle();
HSSFDataFormat dataFormat = workbook.createDataFormat();
dateStyle.setDataFormat(dataFormat.getFormat("yyyy-mm-dd"));
//遍历设置格式
for (int i = 3; i <400; i++) {
row = sheet.createRow(i);
for (int j = 9; j <=11; j++) {
cell = row.createCell(j);
cell.setCellStyle(dateStyle);
}
}
//ps:这样设置格式后在使用该模板进行excel导入操作时,会被算存在一行,请先判断不为空再操作
6 生成后返回给前端
6.1 后端发送
HSSFWorkbook workbook = testService.getExportXls();
OutputStream osOut = null;
try{
osOut = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment;");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setCharacterEncoding("utf-8");
workbook.write(osOut);
osOut.flush();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if(osOut != null){
osOut.close();
}
workbook.close();
}catch (IOException e){
e.printStackTrace();
}
}
6.2 前端接收
//绑定某个按钮
downloadXls(){
//使用什么请求看自己需要
request({
url: `/后端的请求路径`,
method: "get",
responseType: 'blob'
}).then(res=>{
let url = window.URL.createObjectURL(new Blob([res], { type: 'application/vnd.ms-excel' }))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', '文件名称.xls')
document.body.appendChild(link)
link.click()
document.body.removeChild(link) //下载完成移除元素
window.URL.revokeObjectURL(url) //释放掉blob对象
})
}