Vue
<a id="download" />
async downloadFktz() {
const res = await riskStandingBookApi.exportFktz(this.queryForm)
if (res.code === 200) {
document.getElementById('download').setAttribute('href', 'data:xlsx;base64,' + res.data)
document.getElementById('download').setAttribute('download', 'a.xlsx')
document.getElementById('download').click()
this.$message.success(res.msg)
} else {
this.$message.error(res.msg)
}
}
Java
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
package com.xxx.xxx.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ExcelUtil {
public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
public static final String EMPTY = "";
public static final String POINT = ".";
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
public static String getValue(Cell cell){
if(cell == null){
return "";
}
String cellValue = "";
int cellType=cell.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_NUMERIC:
short format = cell.getCellStyle().getDataFormat();
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = null;
if (format == 20 || format == 32) {
sdf = new SimpleDateFormat("HH:mm");
} else if (format == 14 || format == 31 || format == 57 || format == 58) {
sdf = new SimpleDateFormat("yyyy-MM-dd");
double value = cell.getNumericCellValue();
Date date = DateUtil
.getJavaDate(value);
cellValue = sdf.format(date);
}else {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
try {
cellValue = sdf.format(cell.getDateCellValue());
} catch (Exception e) {
try {
throw new Exception("exception on get date data !".concat(e.toString()));
} catch (Exception e1) {
e1.printStackTrace();
}
}finally{
sdf = null;
}
} else {
BigDecimal bd = new BigDecimal(cell.getNumericCellValue()).setScale(8,BigDecimal.ROUND_HALF_UP);
cellValue = bd.toPlainString();
}
break;
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = cell.getBooleanCellValue()+"";;
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR:
cellValue = "ERROR VALUE";
break;
default:
cellValue = "UNKNOW VALUE";
break;
}
return cellValue;
}
public static Map<String,Integer> getCollIndexNew(Row row){
Map<String,Integer> map = new HashMap<>();
for(int i = 0;i<row.getLastCellNum();i++){
map.put(getValue(row.getCell(i)),i);
}
return map;
}
public static XSSFCellStyle getStyle(XSSFWorkbook workbook, short boldWeight, short fontHeight, short fontColor, short alignment,
short verticalAlignment, short borderBottom, short borderLeft, short borderRight, short borderTop, String dataFormat,
boolean warpText, short fillPattern, XSSFColor xssfColor){
try {
Font font = workbook.createFont();
font.setFontHeightInPoints(fontHeight);
font.setFontName("黑体");
font.setColor(fontColor);
XSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(alignment);
style.setVerticalAlignment(verticalAlignment);
style.setFont(font);
style.setWrapText(false);
if(borderBottom != 0) {
style.setBorderBottom(borderBottom);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
}
if(borderLeft != 0) {
style.setBorderLeft(borderLeft);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
}
if(borderRight != 0) {
style.setBorderRight(borderRight);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
}
if(borderTop != 0) {
style.setBorderTop(borderTop);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
}
style.setWrapText(warpText);
if(fillPattern != 0) {
style.setFillPattern(fillPattern);
}
if(xssfColor != null) {
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(xssfColor);
}
if(StringUtils.isNotBlank(dataFormat)) {
DataFormat df = workbook.createDataFormat();
style.setDataFormat(df.getFormat(dataFormat));
}
return style;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
public static XSSFCellStyle getStyle(XSSFWorkbook workbook,short boldWeight,short fontHeight,short fontColor,short alignment,
short verticalAlignment,short borderBottom,short borderLeft,short borderRight,short borderTop,String dataFormat,
boolean warpText,short fillPattern,short fillForegroundColor){
try {
Font font = workbook.createFont();
font.setFontHeightInPoints(fontHeight);
font.setFontName("黑体");
font.setColor(fontColor);
XSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(alignment);
style.setVerticalAlignment(verticalAlignment);
style.setFont(font);
style.setWrapText(false);
if(borderBottom != 0) {
style.setBorderBottom(borderBottom);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
}
if(borderLeft != 0) {
style.setBorderLeft(borderLeft);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
}
if(borderRight != 0) {
style.setBorderRight(borderRight);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
}
if(borderTop != 0) {
style.setBorderTop(borderTop);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
}
style.setWrapText(warpText);
if(fillPattern != 0) {
style.setFillPattern(fillPattern);
}
if(fillForegroundColor != 0) {
style.setFillForegroundColor(fillForegroundColor);
}
if(StringUtils.isNotBlank(dataFormat)) {
DataFormat df = workbook.createDataFormat();
style.setDataFormat(df.getFormat(dataFormat));
}
return style;
}catch (Exception e){
return null;
}
}
public static CellStyle getStyle(Workbook workbook,short boldWeight,short fontHeight,short fontColor,short alignment,
short verticalAlignment,short borderBottom,short borderLeft,short borderRight,short borderTop,String dataFormat,
boolean warpText,short fillPattern,short fillForegroundColor){
try {
Font font = workbook.createFont();
font.setFontHeightInPoints(fontHeight);
font.setFontName("黑体");
font.setColor(fontColor);
font.setBoldweight(boldWeight);
CellStyle style = workbook.createCellStyle();
style.setAlignment(alignment);
style.setVerticalAlignment(verticalAlignment);
style.setFont(font);
style.setWrapText(false);
if(borderBottom != 0) {
style.setBorderBottom(borderBottom);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
}
if(borderLeft != 0) {
style.setBorderLeft(borderLeft);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
}
if(borderRight != 0) {
style.setBorderRight(borderRight);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
}
if(borderTop != 0) {
style.setBorderTop(borderTop);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
}
style.setWrapText(warpText);
if(fillPattern != 0) {
style.setFillPattern(fillPattern);
}
if(fillForegroundColor != 0) {
style.setFillForegroundColor(fillForegroundColor);
}
if(StringUtils.isNotBlank(dataFormat)) {
DataFormat df = workbook.createDataFormat();
style.setDataFormat(df.getFormat(dataFormat));
}
return style;
}catch (Exception e){
return null;
}
}
public static String getPostfix(String path){
if(path==null || EMPTY.equals(path.trim())){
return EMPTY;
}
if(path.contains(POINT)){
return path.substring(path.lastIndexOf(POINT)+1,path.length());
}
return EMPTY;
}
@SuppressWarnings({ "static-access", "deprecation" })
static class XSSFDateUtil extends DateUtil {
protected static int absoluteDay(Calendar cal, boolean use1904windowing) {
return DateUtil.absoluteDay(cal, use1904windowing);
}
}
}
@RequestMapping(value = "/exportFktz",method = RequestMethod.POST)
@ResponseBody
public RestResponse<String> exportFktz(@RequestBody TrsRiskStandingBookSearchDto model){
try {
String result = trsRiskStandingBookService.exportFktz(model);
return new RestResponse<String>(RestResponse.SUCCESS_CODE,"导出成功", result);
} catch (Exception e) {
e.printStackTrace();
return new RestResponse<String>(RestResponse.FAILURE_CODE,"导出失败" + e.getMessage(),null);
}
}
@Override
public String exportFktz(TrsRiskStandingBookSearchDto dto) {
long userId = StpUtil.getLoginIdAsLong();
List<TrsBasicsProjectModel> basicsProjectModelList = trsBasicsProjectMapper.queryUserProject(userId);
LambdaQueryWrapper<TrsRiskStandingBookModel> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.in(CollUtil.isNotEmpty(dto.getProjectIds()), TrsRiskStandingBookModel::getProjectId, dto.getProjectIds());
queryWrapper.in(!CollectionUtils.isEmpty(basicsProjectModelList), TrsRiskStandingBookModel::getProjectId
, basicsProjectModelList.stream().map(BaseModel::getId).collect(Collectors.toList()));
queryWrapper.in(CollUtil.isNotEmpty(dto.getStrategyIds()), TrsRiskStandingBookModel::getStrategyId, dto.getStrategyIds());
queryWrapper.ge(StringUtils.isNotBlank(dto.getBeginDate()), TrsRiskStandingBookModel::getDate, dto.getBeginDate());
queryWrapper.le(StringUtils.isNotBlank(dto.getEndDate()), TrsRiskStandingBookModel::getDate, dto.getEndDate());
List<TrsRiskStandingBookModel> modelList = trsRiskStandingBookMapper.selectList(queryWrapper);
modelList = modelList.stream().sorted(Comparator.comparing(TrsRiskStandingBookModel::getDate).reversed()).collect(Collectors.toList());
for (TrsRiskStandingBookModel bookModel : modelList) {
translateFktz(bookModel);
}
if (!CollectionUtils.isEmpty(modelList)) {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("a");
sheet.setDefaultColumnWidth(15);
int rowNum = 0;
Row row0 = sheet.createRow(rowNum++);
Cell cell0_0 = row0.createCell(0);
cell0_0.setCellValue("1");
cell0_0.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
Cell cell0_1 = row0.createCell(1);
cell0_1.setCellValue("2");
cell0_1.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
Cell cell0_2 = row0.createCell(2);
cell0_2.setCellValue("3");
cell0_2.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
Cell cell0_3 = row0.createCell(3);
cell0_3.setCellValue("4");
cell0_3.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
Cell cell0_4 = row0.createCell(4);
cell0_4.setCellValue("5");
cell0_4.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
Cell cell0_5 = row0.createCell(5);
cell0_5.setCellValue("6");
cell0_5.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
Cell cell0_6 = row0.createCell(6);
cell0_6.setCellValue("7");
cell0_6.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
Cell cell0_7 = row0.createCell(7);
cell0_7.setCellValue("8");
cell0_7.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
Cell cell0_8 = row0.createCell(8);
cell0_8.setCellValue("9");
cell0_8.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
Cell cell0_9 = row0.createCell(9);
cell0_9.setCellValue("10");
cell0_9.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
for (TrsRiskStandingBookModel bookModel : modelList) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(bookModel.getDate());
row.createCell(1).setCellValue(bookModel.getProjectName());
row.createCell(2).setCellValue(bookModel.getStrategyType());
row.createCell(3).setCellValue(bookModel.getStrategyName());
row.createCell(4).setCellValue(null == bookModel.getPosition()
? null : bookModel.getPosition().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
if (StringUtils.isNotBlank(dto.getMoneyUnit()) && "万元".equals(dto.getMoneyUnit())) {
row.createCell(5).setCellValue(null == bookModel.getClyk()
? null : bookModel.getClyk().divide(new BigDecimal("10000"),2,BigDecimal.ROUND_HALF_UP).toString());
row.createCell(6).setCellValue(null == bookModel.getClykdrzl()
? null : bookModel.getClykdrzl().divide(new BigDecimal("10000"),2, BigDecimal.ROUND_HALF_UP).toString());
}else {
row.createCell(5).setCellValue(null == bookModel.getClyk()
? null : bookModel.getClyk().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
row.createCell(6).setCellValue(null == bookModel.getClykdrzl()
? null : bookModel.getClykdrzl().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
}
row.createCell(7).setCellValue(null == bookModel.getExposure()
? null : bookModel.getExposure().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
row.createCell(8).setCellValue(null == bookModel.getHedgingRate()
? null : bookModel.getHedgingRate().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
row.createCell(9).setCellValue(bookModel.getRemark());
}
String fileTempPath = System.getProperty("user.dir") + File.separator + "tempExcel";
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
File f = new File(fileTempPath);
if (!f.exists()) {
f.mkdir();
}
FileOutputStream fos = new FileOutputStream(fileTempPath + File.separator + sdf.format(now) + "a.xlsx");
workbook.write(fos);
fos.flush();
fos.close();
File file = new File(fileTempPath + File.separator + sdf.format(now) + "a.xlsx");
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
return new BASE64Encoder().encode(buffer);
} catch (Exception e) {
throw new RuntimeException("生成Excel异常", e);
}
}
return null;
}