当前位置:网站首页>Easypoi export table with echars chart
Easypoi export table with echars chart
2022-07-28 07:09:00 【Fu Hua-】
effect

Realize the idea
The front-end chart uses echars Show , Just let the front end put the chart in the form of pictures , Picture the base64 coming , The back end receives this base64, Written to the workbook sheet Then you can . Whether it's a line chart 、 The pie chart 、 The histogram is the same , Append the picture as a picture to sheet in , Just set the offset of the chart .
Realization
1、ExcelStyleUtil Export style tool class
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.params.ExcelForEachParams;
import cn.afterturn.easypoi.excel.export.styler.IExcelExportStyler;
import org.apache.poi.ss.usermodel.*;
public class ExcelStyleUtil implements IExcelExportStyler {
private static final short STRING_FORMAT = (short) BuiltinFormats.getBuiltinFormat("TEXT");
private static final short FONT_SIZE_TEN = 12;
private static final short FONT_SIZE_ELEVEN = 14;
private static final short FONT_SIZE_TWELVE = 18;
/** * Headline style */
private CellStyle headerStyle;
/** * Each column header style */
private CellStyle titleStyle;
/** * Data line style */
private CellStyle styles;
public ExcelStyleUtil(Workbook workbook) {
this.init(workbook);
}
/** * Initialize style * @param workbook */
private void init(Workbook workbook) {
this.headerStyle = initHeaderStyle(workbook);
this.titleStyle = initTitleStyle(workbook,true,FONT_SIZE_ELEVEN);
this.styles = initStyles(workbook);
}
@Override
public CellStyle getHeaderStyle(short i) {
return headerStyle;
}
@Override
public CellStyle getTitleStyle(short i) {
return titleStyle;
}
@Override
public CellStyle getTemplateStyles(boolean b, ExcelForEachParams excelForEachParams) {
return null;
}
@Override
public CellStyle getStyles(boolean b, ExcelExportEntity excelExportEntity) {
return styles;
}
@Override
public CellStyle getStyles(Cell cell, int i, ExcelExportEntity entity, Object o, Object o1) {
return getStyles(true, entity);
}
/** * Set interlaced background color */
public static CellStyle getStyles(Workbook workbook,boolean isBold,short size) {
CellStyle style = initTitleStyle(workbook,isBold,size);
style.setDataFormat(STRING_FORMAT);
return style;
}
/** * initialization -- Headline style */
private static CellStyle initHeaderStyle(Workbook workbook) {
CellStyle style = getBaseCellStyle(workbook);
style.setFont(getFont(workbook, FONT_SIZE_TWELVE, true));
return style;
}
/** * initialization -- Each column header style */
private static CellStyle initTitleStyle(Workbook workbook,boolean isBold,short size) {
CellStyle style = getBaseCellStyle(workbook);
style.setFont(getFont(workbook, size, isBold));
// Background color
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
return style;
}
/** * initialization -- Data line style */
private static CellStyle initStyles(Workbook workbook) {
CellStyle style = getBaseCellStyle(workbook);
style.setFont(getFont(workbook, FONT_SIZE_TEN, false));
style.setDataFormat(STRING_FORMAT);
return style;
}
/** * Basic style */
private static CellStyle getBaseCellStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// Under the frame
style.setBorderBottom(BorderStyle.THIN);
// The left margin
style.setBorderLeft(BorderStyle.THIN);
// On the border
style.setBorderTop(BorderStyle.THIN);
// Right margin
style.setBorderRight(BorderStyle.THIN);
// Horizontal center
style.setAlignment(HorizontalAlignment.CENTER);
// Center up and down
style.setVerticalAlignment(VerticalAlignment.CENTER);
// Set auto wrap
style.setWrapText(true);
return style;
}
/** * Font style * @param size font size * @param isBold Is it bold */
private static Font getFont(Workbook workbook, short size, boolean isBold) {
Font font = workbook.createFont();
// Font style
font.setFontName(" Song style ");
// Is it bold
font.setBold(isBold);
// font size
font.setFontHeightInPoints(size);
return font;
}
}
2、ExcelUtil Export tool class
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.excel.imports.ExcelImportService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;
public class ExcelUtil {
/** * excel export * @param list data * @param title title * @param sheetName sheet name * @param pojoClass pojo type * @param fileName File name */
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response){
ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
exportParams.setStyle(ExcelStyleUtil.class);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
/** * excel export * @param list data * @param pojoClass pojo type * @param fileName File name */
public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response){
ExportParams exportParams = new ExportParams();
exportParams.setStyle(ExcelStyleUtil.class);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
/** * list map export * @param list data * @param fileName File name */
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
ExportParams exportParams = new ExportParams();
exportParams.setStyle(ExcelStyleUtil.class);
defaultExport(list, fileName, response);
}
/** * default excel export * @param list data * @param pojoClass pojo type * @param fileName File name * @param exportParams Export parameters */
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams){
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
}
/** * default excel export * @param list data * @param fileName File name */
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.XSSF);
downLoadExcel(fileName, response, workbook);
}
/** * download * @param fileName File name * @param response * @param workbook excel data */
public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook){
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLS.getValue(), "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
/** * excel Import * @param filePath excel File path * @param titleRows Title Line * @param headerRows Header row * @param pojoClass pojo type */
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
if (StringUtils.isBlank(filePath)) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setNeedSave(true);
params.setSaveUrl("/excel/");
try {
return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException(" Template cannot be empty ");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/** * excel Import * @param file Uploaded files * @param titleRows Title Line * @param headerRows Header row * @param needVerify Is it inspected excel Content * @param pojoClass pojo type */
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerify, Class<T> pojoClass) throws IOException {
if (file == null) {
return null;
}
try {
return importExcel(file.getInputStream(), titleRows, headerRows, needVerify, pojoClass);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/** * excel Import * @param inputStream File input stream * @param titleRows Title Line * @param headerRows Header row * @param needVerify Is it inspected excel Content * @param pojoClass pojo type */
public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerify, Class<T> pojoClass) throws IOException {
if (inputStream == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setSaveUrl("upload/excel/");
params.setNeedSave(true);
params.setNeedVerify(needVerify);
try {
return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("excel The file cannot be empty ");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/** * Excel Enumeration type */
enum ExcelTypeEnum {
XLS("xls"), XLSX("xlsx");
private String value;
ExcelTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
/** * Upload files , Return to one workbook * @param file */
public static Workbook importExcel(MultipartFile file) throws IOException {
File toFile = new File(file.getOriginalFilename());
Workbook workbook = null;
if(toFile.getPath().endsWith("xls")){
workbook = new HSSFWorkbook(file.getInputStream());
}else if(toFile.getPath().endsWith("xlsx")){
workbook = new XSSFWorkbook(file.getInputStream());
}else {
throw new RuntimeException(" Please confirm the file type you uploaded ");
}
return workbook;
}
/** * Read specified sheet The data of * @param file Uploaded files * @param sheetName To read the sheetName * @param titleRows Number of header lines * @param headRows Number of header lines * @param startRows How many rows of unwanted data are there before the header , from 1 Start , Ignore empty lines * @param readRows How many rows of data to read , from 0 Start , For example, read ten lines , The value is 9; If not specified, it defaults to 0 * @param pojoClass Entity */
public static <T> List<T> importExcel(MultipartFile file,String sheetName,Integer titleRows,Integer headRows, Integer startRows,Integer readRows,Class<T> pojoClass) throws Exception {
Workbook workbook = importExcel(file);
int numberOfSheets = workbook.getNumberOfSheets();
List<T> list = null;
for (int i = 0; i < numberOfSheets; i++) {
String name = workbook.getSheetName(i).trim();
if (name.equals(sheetName) || name.endsWith(sheetName)){
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headRows);
params.setStartRows(startRows);
params.setReadRows(readRows);
// Number one sheet page
params.setStartSheetIndex(i);
final ExcelImportService excelImportService = new ExcelImportService();
ExcelImportResult<T> result = excelImportService.importExcelByIs(file.getInputStream(), pojoClass, params, false);
list = result.getList();
break;
}
}
return list;
}
/** * export Excel, And add pictures at the end * @param sheetName sheet name * @param wb Workbook object * @param imgUrl The image base64 character string */
public static Workbook getWorkbook(String sheetName,Workbook wb, String imgUrl) throws IOException {
if (wb == null) {
wb = new HSSFWorkbook();
}
// stay workbook According to the sheet Name gets the specified sheet
Sheet sheet = wb.getSheet(sheetName);
/* Generate charts */
if(!StringUtils.isEmpty(imgUrl)) {
// Split base64 After coding
String[] imgUrlArr = imgUrl.split("base64,");
byte[] buffer = new BASE64Decoder().decodeBuffer(imgUrlArr[1]);
// Temporary storage address of pictures
String picPath = System.getProperty("user.dir")+"\\upload\\image\\pic.png";
// Picture file
File file = new File(picPath);
try {
// Generate pictures
OutputStream out = new FileOutputStream(file);// Image output stream
out.write(buffer);
out.flush();// Empty the stream
out.close();// Closed flow
// Write pictures to the stream
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
BufferedImage bufferImg = ImageIO.read(new File(picPath));
ImageIO.write(bufferImg, "PNG", outStream);
// utilize Drawing Write pictures to EXCEL
Drawing<?> drawing = sheet.createDrawingPatriarch();
// Set chart offset : The first 1 In cells x Offset of axis 、 The first 1 In cells y Offset of axis 、 The first 2 In cells x Offset of axis 、 The first 2 In cells y Offset of axis 、 The first 1 Column number of cells 、 The first 1 Line number of cells 、 The first 2 Column number of cells 、 The first 2 Line number of cells
//HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 6, (short) 9, 40);
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 6, 9, 40);
drawing.createPicture(anchor, wb.addPicture(outStream.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
} catch (Exception ex) {
ex.printStackTrace();
}
if (file.exists()) {
file.delete();// Delete pictures
}
}
return wb;
}
}
3、controller
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.common.util.ExcelStyleUtil;
import com.common.util.ExcelUtil;
import lombok.Data;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/test")
public class TestController {
@Data
public static class Test{
@Excel(name = " name ",width = 25)
private String name;
@Excel(name = "1 month ",width = 15)
private Double m1;
@Excel(name = "2 month ",width = 15)
private Double m2;
@Excel(name = "3 month ",width = 15)
private Double m3;
@Excel(name = "4 month ",width = 15)
private Double m4;
@Excel(name = "5 month ",width = 15)
private Double m5;
@Excel(name = "6 month ",width = 15)
private Double m6;
@Excel(name = "7 month ",width = 15)
private Double m7;
@Excel(name = "8 month ",width = 15)
private Double m8;
@Excel(name = "9 month ",width = 15)
private Double m9;
@Excel(name = "10 month ",width = 15)
private Double m10;
@Excel(name = "11 month ",width = 15)
private Double m11;
@Excel(name = "12 month ",width = 15)
private Double m12;
public Test(String name, Double m1, Double m2, Double m3, Double m4, Double m5, Double m6, Double m7, Double m8, Double m9, Double m10, Double m11, Double m12) {
this.name = name;
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
this.m4 = m4;
this.m5 = m5;
this.m6 = m6;
this.m7 = m7;
this.m8 = m8;
this.m9 = m9;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
}
}
@PostMapping("/export")
public void export(String imgUrl, HttpServletResponse response) throws IOException {
List<Test> list = new ArrayList<>();
list.add(new Test(" Industry ",885.0,845.0,832.0,878.0,996.0,763.0,820.0,848.0,798.0,925.0,933.0,777.96));
list.add(new Test(" Agriculture ",224.32,177.0,141.75,231.23,254.22,300.25,244.32,177.88,123.0,280.88,235.74,333.0));
list.add(new Test(" business ",650.36,622.25,672.47,599.0,548.0,621.36,647.14,420.25,752.98,600.75,567.1,643.0));
list.add(new Test(" other ",444.3,486.0,421.24,431.22,333.1,420.28,398.74,385.57,324.0,420.75,421.12,468.0));
ExportParams params = new ExportParams();
params.setTitle(" Annual electricity statistics ");
params.setTitleHeight((short) 15);
params.setHeight((short) 12);
params.setStyle(ExcelStyleUtil.class);
params.setSheetName(" Electricity Statistics ");
Workbook workbook = ExcelExportUtil.exportExcel(params,Test.class, list);
workbook = ExcelUtil.getWorkbook(" Electricity Statistics ", workbook, imgUrl);
ExcelUtil.downLoadExcel(" Annual electricity statistics ",response,workbook);
}
}
边栏推荐
猜你喜欢

PXE unattended installation management

MOOC翁恺C语言 第四周:进一步的判断与循环:1.逻辑类型与运算2.级联和嵌套的判断

DOM -- page rendering, style attribute operation, preloading and lazy loading, anti shake and throttling

About gcc:multiple definition of

DOM operation cases

MOOC翁恺C语言 第四周:进一步的判断与循环:3.多路分支4.循环的例子5.判断和循环常见的错误

MOOC Weng Kai C language week 6: arrays and functions: 1. Arrays 2. Definition and use of functions 3. Parameters and variables of functions 4. Two dimensional arrays

DNS域名解析

Esxi community nvme driver update v1.1

Icc2 analysis timing artifact analyze_ design_ violations
随机推荐
DHCP服务
MOOC翁恺C语言 第四周:进一步的判断与循环:3.多路分支4.循环的例子5.判断和循环常见的错误
Svg understanding and drawing application
YUM仓库的搭建
Operation document tree
MOOC翁恺C语言第五周:1.循环控制2.多重循环3.循环应用
在转化词向量之前先转化为AST再转化为词向量的实现方法
Implementation method of Bert
[learning notes] knowledge management
Applet navigator cannot jump (debug)
Escape character notes
Static and floating routes
shell---sed语句练习
Servlet
Joern的代码使用-devign
Neo4j running error occurred during initialization of VM incompatible minimum and maximum heap sizes spec
MOOC Weng Kai C language fourth week: further judgment and circulation: 1. Logical types and operations 2. Judgment of cascading and nesting
shell---函数
VSphere esxi 7.0 update 3 release notes
Results fill in the blanks carelessly (violent solution)