当前位置:网站首页>Freemaker+poi realizes dynamic generation and parsing of Excel files
Freemaker+poi realizes dynamic generation and parsing of Excel files
2022-07-02 17:59:00 【Stay for love】
freemarker+poi Dynamic generation excel file
pom File configuration :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>The configuration file :
# Template suffix
spring.freemarker.suffix:.ftl
# The document type
spring.freemarker.content-type:text/html
# The page code
spring.freemarker.charset:UTF-8
# Page caching
spring.freemarker.cache:false
# Template path
spring.freemarker.template-loader-path:classpath:/templates/
Generate template ftl File steps :
1、 newly build excel file :test.xlsx

2、 Save the file as xml file , namely test.xml
3、 hold test.xml Modify the file suffix , Change it to test.ftl
4、ftl File format On-line XML format | Rookie tools
5、test.ftl Add dynamic data parameters to the file
<#if userList??>
<#list userList as user>
<Row>
<Cell>
<Data ss:Type="String">${user.name}</Data>
</Cell>
<Cell>
<Data ss:Type="Number">${user.age}</Data>
</Cell>
<Cell ss:StyleID="s51" ss:HRef="mailto:${user.email}">
<Data ss:Type="String">${user.email}</Data>
</Cell>
</Row>
</#list>
</#if>Finally put test.ftl Files in resources/templates Next ,freemarker The default location for reading template files
Use springboot+freemarker Dynamically generate and download online excel file
package com.example.stu1.freemark;
import lombok.Data;
/**
* @Author yangcai
* @create 2022/7/1 16:43
*/
@Data
public class User {
private int age;
private String name;
private String email;
}
import freemarker.template.Template;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author yangcai
* @create 2022/7/1 16:43
*/
@RestController
public class UserController {
@Resource
FreeMarkerConfigurer freemarkerConfigurer;
@GetMapping("/index")
public void index(HttpServletResponse response) {
String userName ="userName";
String fileName = userName +" Test the exported " + ".xlsx";
Map<String,Object> resultMap= getList();
downloadDoc(freemarkerConfigurer, "/test.ftl", resultMap, fileName, response);
}
Map<String,Object> getList(){
Map<String,Object> map = new HashMap<>();
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setAge(26);
user1.setEmail("[email protected]");
user1.setName(" zhang wuji ");
userList.add(user1);
User user2 = new User();
user2.setAge(27);
user2.setEmail("[email protected]");
user2.setName(" Xiaoyao Zi ");
userList.add(user2);
User user3 = new User();
user3.setAge(28);
user3.setEmail("[email protected]");
user3.setName(" Xiao feng ");
userList.add(user3);
map.put("userList",userList);
return map;
}
public void downloadDoc(FreeMarkerConfigurer freemarkerConfigurer, String modelPath, Map<String, Object> data,
String fileName, HttpServletResponse response) {
try {
Template template = freemarkerConfigurer.getConfiguration().getTemplate(modelPath);
response.reset();
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
PrintWriter writer = response.getWriter();
template.process(data, writer);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}request :http://localhost:8080/index
Will generate a xlsx file : The contents of the document are as follows

Be careful : This excel The essence of the document is still a xml file , use WPS Can open normally , But with office Opening will prompt that the file format is incorrect

So we should really generate excel, You also need to use poi,poi The purpose of this project is to xml File conversion to excel file
pom introduce poi relevant jar:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>cn.eonml</groupId>
<artifactId>freemarker-excel</artifactId>
<version>0.1.5</version>
</dependency>Custom tool class :
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.example.stu1.freemark;
import com.yongjiu.commons.utils.XmlReader;
import com.yongjiu.dto.freemarker.input.ExcelImageInput;
import com.yongjiu.dto.freemarker.input.FreemarkerInput;
import com.yongjiu.entity.excel.Cell;
import com.yongjiu.entity.excel.CellRangeAddressEntity;
import com.yongjiu.entity.excel.Column;
import com.yongjiu.entity.excel.Data;
import com.yongjiu.entity.excel.Row;
import com.yongjiu.entity.excel.Style;
import com.yongjiu.entity.excel.Table;
import com.yongjiu.entity.excel.Worksheet;
import com.yongjiu.entity.excel.Style.Border;
import com.yongjiu.util.ColorUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
public class FreeMarkerTemplateUtil {
private static final Logger log = LoggerFactory.getLogger(FreeMarkerTemplateUtil.class);
public FreeMarkerTemplateUtil() {
}
public static void exportToFile(Map dataMap, String templateName, String templateFilePath, String fileFullPath) {
try {
File file = new File(fileFullPath);
FileUtils.forceMkdirParent(file);
FileOutputStream outputStream = new FileOutputStream(file);
exportToStream(dataMap, templateName, templateFilePath, outputStream);
} catch (Exception var6) {
var6.printStackTrace();
}
}
public static void exportToStream(Map dataMap, String templateName, String templateFilePath, FileOutputStream outputStream) {
try {
Template template = getTemplate(templateName, templateFilePath);
OutputStreamWriter outputWriter = new OutputStreamWriter(outputStream, "UTF-8");
Writer writer = new BufferedWriter(outputWriter);
template.process(dataMap, writer);
writer.flush();
writer.close();
outputStream.close();
} catch (Exception var7) {
var7.printStackTrace();
}
}
public static void exportImageExcel(String excelFilePath, FreemarkerInput freemarkerInput) {
try {
File file = new File(excelFilePath);
FileUtils.forceMkdirParent(file);
FileOutputStream outputStream = new FileOutputStream(file);
createImageExcleToStream(freemarkerInput, outputStream);
FileUtils.forceDelete(new File(freemarkerInput.getXmlTempFile() + freemarkerInput.getFileName() + ".xml"));
log.info(" Export succeeded , Export to directory :" + file.getCanonicalPath());
} catch (Exception var4) {
var4.printStackTrace();
}
}
public static void exportImageExcelNew(String excelFilePath, FreemarkerInput freemarkerInput) {
try {
File file = new File(excelFilePath);
FileUtils.forceMkdirParent(file);
FileOutputStream outputStream = new FileOutputStream(file);
createExcelToStream(freemarkerInput, outputStream);
FileUtils.forceDelete(new File(freemarkerInput.getXmlTempFile() + freemarkerInput.getFileName() + ".xml"));
log.info(" Export succeeded , Export to directory :" + file.getCanonicalPath());
} catch (Exception var4) {
var4.printStackTrace();
}
}
public static void exportImageExcelNew(HttpServletResponse response, FreemarkerInput freemarkerInput) {
try {
OutputStream outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/msexcel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=\"" + new String((freemarkerInput.getFileName() + ".xlsx").getBytes("GBK"), "ISO8859-1") + "\"");
response.setHeader("Response-Type", "Download");
createExcelToStream(freemarkerInput, outputStream);
FileUtils.forceDelete(new File(freemarkerInput.getXmlTempFile() + freemarkerInput.getFileName() + ".xml"));
} catch (Exception var3) {
var3.printStackTrace();
}
}
public static void exportImageExcel(HttpServletResponse response, FreemarkerInput freemarkerInput) {
try {
OutputStream outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/msexcel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=\"" + new String((freemarkerInput.getFileName() + ".xls").getBytes("GBK"), "ISO8859-1") + "\"");
response.setHeader("Response-Type", "Download");
createImageExcleToStream(freemarkerInput, outputStream);
FileUtils.forceDelete(new File(freemarkerInput.getXmlTempFile() + freemarkerInput.getFileName() + ".xml"));
} catch (Exception var3) {
var3.printStackTrace();
}
}
private static Template getTemplate(String templateName, String filePath) throws IOException {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
configuration.setDefaultEncoding("UTF-8");
configuration.setTemplateUpdateDelayMilliseconds(0L);
configuration.setEncoding(Locale.CHINA, "UTF-8");
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
configuration.setClassForTemplateLoading(FreeMarkerTemplateUtil.class, filePath);
configuration.setOutputEncoding("UTF-8");
return configuration.getTemplate(templateName, "UTF-8");
}
private static void createImageExcleToStream(FreemarkerInput freemarkerInput, OutputStream outputStream) {
BufferedWriter out = null;
try {
Template template = getTemplate(freemarkerInput.getTemplateName(), freemarkerInput.getTemplateFilePath());
File tempXMLFile = new File(freemarkerInput.getXmlTempFile() + freemarkerInput.getFileName() + ".xml");
FileUtils.forceMkdirParent(tempXMLFile);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempXMLFile), "UTF-8"));
template.process(freemarkerInput.getDataMap(), out);
if (log.isDebugEnabled()) {
log.debug("1. Finish importing text data into XML In file ");
}
SAXReader reader = new SAXReader();
Document document = reader.read(tempXMLFile);
Map<String, Style> styleMap = readXmlStyle(document);
log.debug("2. Finish parsing XML Style information in ");
List<Worksheet> worksheets = readXmlWorksheet(document);
if (log.isDebugEnabled()) {
log.debug("3. Begin to XML iw Excel, The data is :" + worksheets.toString());
}
HSSFWorkbook wb = new HSSFWorkbook();
Iterator var10 = worksheets.iterator();
while(var10.hasNext()) {
Worksheet worksheet = (Worksheet)var10.next();
HSSFSheet sheet = wb.createSheet(worksheet.getName());
Table table = worksheet.getTable();
List<Row> rows = table.getRows();
List<Column> columns = table.getColumns();
int createRowIndex;
if (columns != null && columns.size() > 0) {
createRowIndex = 0;
for(int i = 0; i < columns.size(); ++i) {
Column column = (Column)columns.get(i);
createRowIndex = getCellWidthIndex(createRowIndex, i, column.getIndex());
sheet.setColumnWidth(createRowIndex, (int)column.getWidth() * 50);
}
}
createRowIndex = 0;
List<CellRangeAddressEntity> cellRangeAddresses = new ArrayList();
for(int rowIndex = 0; rowIndex < rows.size(); ++rowIndex) {
Row rowInfo = (Row)rows.get(rowIndex);
if (rowInfo != null) {
createRowIndex = getIndex(createRowIndex, rowIndex, rowInfo.getIndex());
HSSFRow row = sheet.createRow(createRowIndex);
if (rowInfo.getHeight() != null) {
Integer height = rowInfo.getHeight() * 20;
row.setHeight(height.shortValue());
}
List<Cell> cells = rowInfo.getCells();
if (!CollectionUtils.isEmpty(cells)) {
int startIndex = 0;
for(int cellIndex = 0; cellIndex < cells.size(); ++cellIndex) {
Cell cellInfo = (Cell)cells.get(cellIndex);
if (cellInfo != null) {
startIndex = getIndex(startIndex, cellIndex, cellInfo.getIndex());
HSSFCell cell = row.createCell(startIndex);
String styleID = cellInfo.getStyleID();
Style style = (Style)styleMap.get(styleID);
CellStyle dataStyle = wb.createCellStyle();
setBorder(style, dataStyle);
setAlignment(style, dataStyle);
setValue((HSSFWorkbook)wb, cellInfo, (HSSFCell)cell, style, dataStyle);
setCellColor(style, dataStyle);
cell.setCellStyle(dataStyle);
if (cellInfo.getComment() != null) {
Data data = cellInfo.getComment().getData();
Comment comment = sheet.createDrawingPatriarch().createCellComment(new HSSFClientAnchor(0, 0, 0, 0, (short)3, 3, (short)5, 6));
comment.setString(new HSSFRichTextString(data.getText()));
cell.setCellComment(comment);
}
startIndex = getCellRanges(createRowIndex, cellRangeAddresses, startIndex, cellInfo, style);
}
}
}
}
}
addCellRange((HSSFSheet)sheet, cellRangeAddresses);
}
log.debug("4. Start writing pictures :" + freemarkerInput.getExcelImageInputs());
if (!CollectionUtils.isEmpty(freemarkerInput.getExcelImageInputs())) {
writeImageToExcel(freemarkerInput.getExcelImageInputs(), wb);
}
log.debug("5. Finish writing pictures :" + freemarkerInput.getExcelImageInputs());
wb.write(outputStream);
outputStream.close();
} catch (Exception var39) {
var39.printStackTrace();
log.error(" export excel abnormal :" + var39.getMessage());
} finally {
try {
out.close();
} catch (Exception var38) {
}
}
}
private static void createExcelToStream(FreemarkerInput freemarkerInput, OutputStream outputStream) {
BufferedWriter out = null;
try {
Template template = getTemplate(freemarkerInput.getTemplateName(), freemarkerInput.getTemplateFilePath());
File tempXMLFile = new File(freemarkerInput.getXmlTempFile() + freemarkerInput.getFileName() + ".xml");
FileUtils.forceMkdirParent(tempXMLFile);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempXMLFile), "UTF-8"));
template.process(freemarkerInput.getDataMap(), out);
if (log.isDebugEnabled()) {
log.debug("1. Finish importing text data into XML In file ");
}
SAXReader reader = new SAXReader();
Document document = reader.read(tempXMLFile);
Map<String, Style> styleMap = readXmlStyle(document);
log.debug("2. Finish parsing XML Style information in ");
List<Worksheet> worksheets = readXmlWorksheet(document);
if (log.isDebugEnabled()) {
log.debug("3. Begin to XML iw Excel, The data is :" + worksheets.toString());
}
XSSFWorkbook wb = new XSSFWorkbook();
Iterator var10 = worksheets.iterator();
while(var10.hasNext()) {
Worksheet worksheet = (Worksheet)var10.next();
XSSFSheet sheet = wb.createSheet(worksheet.getName());
Table table = worksheet.getTable();
List<Row> rows = table.getRows();
List<Column> columns = table.getColumns();
int createRowIndex;
if (columns != null && columns.size() > 0) {
createRowIndex = 0;
for(int i = 0; i < columns.size(); ++i) {
Column column = (Column)columns.get(i);
createRowIndex = getCellWidthIndex(createRowIndex, i, column.getIndex());
sheet.setColumnWidth(createRowIndex, (int)column.getWidth() * 50);
}
}
for(int i = 0 ; i<1000;i++){
sheet.setColumnWidth(i,3000);
}
createRowIndex = 0;
List<CellRangeAddressEntity> cellRangeAddresses = new ArrayList();
for(int rowIndex = 0; rowIndex < rows.size(); ++rowIndex) {
Row rowInfo = (Row)rows.get(rowIndex);
if (rowInfo != null) {
createRowIndex = getIndex(createRowIndex, rowIndex, rowInfo.getIndex());
XSSFRow row = sheet.createRow(createRowIndex);
if (rowInfo.getHeight() != null) {
Integer height = rowInfo.getHeight() * 20;
row.setHeight(height.shortValue());
}
List<Cell> cells = rowInfo.getCells();
if (!CollectionUtils.isEmpty(cells)) {
int startIndex = 0;
for(int cellIndex = 0; cellIndex < cells.size(); ++cellIndex) {
Cell cellInfo = (Cell)cells.get(cellIndex);
if (cellInfo != null) {
startIndex = getIndex(startIndex, cellIndex, cellInfo.getIndex());
XSSFCell cell = row.createCell(startIndex);
String styleID = cellInfo.getStyleID();
Style style = (Style)styleMap.get(styleID);
CellStyle dataStyle = wb.createCellStyle();
setBorder(style, dataStyle);
setAlignment(style, dataStyle);
setValue((XSSFWorkbook)wb, cellInfo, (XSSFCell)cell, style, dataStyle);
setCellColor(style, dataStyle);
cell.setCellStyle(dataStyle);
if (cellInfo.getComment() != null) {
Data data = cellInfo.getComment().getData();
Comment comment = sheet.createDrawingPatriarch().createCellComment(new XSSFClientAnchor(0, 0, 0, 0, 3, 3, 5, 6));
comment.setString(new XSSFRichTextString(data.getText()));
cell.setCellComment(comment);
}
startIndex = getCellRanges(createRowIndex, cellRangeAddresses, startIndex, cellInfo, style);
}
}
}
}
}
addCellRange((XSSFSheet)sheet, cellRangeAddresses);
}
log.debug("4. Start writing pictures :" + freemarkerInput.getExcelImageInputs());
if (!CollectionUtils.isEmpty(freemarkerInput.getExcelImageInputs())) {
writeImageToExcel(freemarkerInput.getExcelImageInputs(), wb);
}
log.debug("5. Finish writing pictures :" + freemarkerInput.getExcelImageInputs());
wb.write(outputStream);
outputStream.close();
} catch (Exception var39) {
var39.printStackTrace();
log.error(" export excel abnormal :" + var39.getMessage());
} finally {
try {
out.close();
} catch (Exception var38) {
}
}
}
public static Map<String, Style> readXmlStyle(Document document) {
Map<String, Style> styleMap = XmlReader.getStyle(document);
return styleMap;
}
public static List<Worksheet> readXmlWorksheet(Document document) {
List<Worksheet> worksheets = XmlReader.getWorksheet(document);
return worksheets;
}
private static int getIndex(int columnIndex, int i, Integer index) {
if (index != null) {
columnIndex = index - 1;
}
if (index == null && columnIndex != 0) {
++columnIndex;
}
if (index == null && columnIndex == 0) {
columnIndex = i;
}
return columnIndex;
}
private static int getCellWidthIndex(int columnIndex, int i, Integer index) {
if (index != null) {
columnIndex = index;
}
if (index == null && columnIndex != 0) {
++columnIndex;
}
if (index == null && columnIndex == 0) {
columnIndex = i;
}
return columnIndex;
}
private static void setBorder(Style style, CellStyle dataStyle) {
if (style != null && style.getBorders() != null) {
for(int k = 0; k < style.getBorders().size(); ++k) {
Border border = (Border)style.getBorders().get(k);
if (border != null) {
if ("Bottom".equals(border.getPosition())) {
dataStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
dataStyle.setBorderBottom(BorderStyle.THIN);
}
if ("Left".equals(border.getPosition())) {
dataStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
dataStyle.setBorderLeft(BorderStyle.THIN);
}
if ("Right".equals(border.getPosition())) {
dataStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
dataStyle.setBorderRight(BorderStyle.THIN);
}
if ("Top".equals(border.getPosition())) {
dataStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
dataStyle.setBorderTop(BorderStyle.THIN);
}
}
}
}
}
private static void writeImageToExcel(List<ExcelImageInput> excelImageInputs, HSSFWorkbook wb) throws IOException {
BufferedImage bufferImg = null;
if (!CollectionUtils.isEmpty(excelImageInputs)) {
Iterator var3 = excelImageInputs.iterator();
while(var3.hasNext()) {
ExcelImageInput excelImageInput = (ExcelImageInput)var3.next();
Sheet sheet = wb.getSheetAt(excelImageInput.getSheetIndex());
if (sheet != null) {
Drawing patriarch = sheet.createDrawingPatriarch();
HSSFClientAnchor anchor = excelImageInput.getAnchorXls();
anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
String imagePath = excelImageInput.getImgPath();
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File(imagePath));
String imageType = imagePath.substring(imagePath.lastIndexOf(".") + 1, imagePath.length());
ImageIO.write(bufferImg, imageType, byteArrayOut);
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), 5));
}
}
}
}
private static void writeImageToExcel(List<ExcelImageInput> excelImageInputs, XSSFWorkbook wb) throws IOException {
BufferedImage bufferImg = null;
if (!CollectionUtils.isEmpty(excelImageInputs)) {
Iterator var3 = excelImageInputs.iterator();
while(var3.hasNext()) {
ExcelImageInput excelImageInput = (ExcelImageInput)var3.next();
Sheet sheet = wb.getSheetAt(excelImageInput.getSheetIndex());
if (sheet != null) {
Drawing patriarch = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = excelImageInput.getAnchorXlsx();
anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
String imagePath = excelImageInput.getImgPath();
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File(imagePath));
String imageType = imagePath.substring(imagePath.lastIndexOf(".") + 1, imagePath.length());
ImageIO.write(bufferImg, imageType, byteArrayOut);
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), 5));
}
}
}
}
private static void addCellRange(HSSFSheet sheet, List<CellRangeAddressEntity> cellRangeAddresses) {
if (!CollectionUtils.isEmpty(cellRangeAddresses)) {
Iterator var2 = cellRangeAddresses.iterator();
while(true) {
CellRangeAddressEntity cellRangeAddressEntity;
CellRangeAddress cellRangeAddress;
do {
if (!var2.hasNext()) {
return;
}
cellRangeAddressEntity = (CellRangeAddressEntity)var2.next();
cellRangeAddress = cellRangeAddressEntity.getCellRangeAddress();
sheet.addMergedRegion(cellRangeAddress);
} while(CollectionUtils.isEmpty(cellRangeAddressEntity.getBorders()));
for(int k = 0; k < cellRangeAddressEntity.getBorders().size(); ++k) {
Border border = (Border)cellRangeAddressEntity.getBorders().get(k);
if (border != null) {
if ("Bottom".equals(border.getPosition())) {
RegionUtil.setBorderBottom(BorderStyle.THIN, cellRangeAddress, sheet);
}
if ("Left".equals(border.getPosition())) {
RegionUtil.setBorderLeft(BorderStyle.THIN, cellRangeAddress, sheet);
}
if ("Right".equals(border.getPosition())) {
RegionUtil.setBorderRight(BorderStyle.THIN, cellRangeAddress, sheet);
}
if ("Top".equals(border.getPosition())) {
RegionUtil.setBorderTop(BorderStyle.THIN, cellRangeAddress, sheet);
}
}
}
}
}
}
private static void addCellRange(XSSFSheet sheet, List<CellRangeAddressEntity> cellRangeAddresses) {
if (!CollectionUtils.isEmpty(cellRangeAddresses)) {
Iterator var2 = cellRangeAddresses.iterator();
while(true) {
CellRangeAddressEntity cellRangeAddressEntity;
CellRangeAddress cellRangeAddress;
do {
if (!var2.hasNext()) {
return;
}
cellRangeAddressEntity = (CellRangeAddressEntity)var2.next();
cellRangeAddress = cellRangeAddressEntity.getCellRangeAddress();
sheet.addMergedRegion(cellRangeAddress);
} while(CollectionUtils.isEmpty(cellRangeAddressEntity.getBorders()));
for(int k = 0; k < cellRangeAddressEntity.getBorders().size(); ++k) {
Border border = (Border)cellRangeAddressEntity.getBorders().get(k);
if (border != null) {
if ("Bottom".equals(border.getPosition())) {
RegionUtil.setBorderBottom(BorderStyle.THIN, cellRangeAddress, sheet);
}
if ("Left".equals(border.getPosition())) {
RegionUtil.setBorderLeft(BorderStyle.THIN, cellRangeAddress, sheet);
}
if ("Right".equals(border.getPosition())) {
RegionUtil.setBorderRight(BorderStyle.THIN, cellRangeAddress, sheet);
}
if ("Top".equals(border.getPosition())) {
RegionUtil.setBorderTop(BorderStyle.THIN, cellRangeAddress, sheet);
}
}
}
}
}
}
private static void setAlignment(Style style, CellStyle dataStyle) {
if (style != null && style.getAlignment() != null) {
String horizontal = style.getAlignment().getHorizontal();
if (!ObjectUtils.isEmpty(horizontal)) {
if ("Left".equals(horizontal)) {
dataStyle.setAlignment(HorizontalAlignment.LEFT);
} else if ("Center".equals(horizontal)) {
dataStyle.setAlignment(HorizontalAlignment.CENTER);
} else {
dataStyle.setAlignment(HorizontalAlignment.RIGHT);
}
}
String vertical = style.getAlignment().getVertical();
if (!ObjectUtils.isEmpty(vertical)) {
if ("Top".equals(vertical)) {
dataStyle.setVerticalAlignment(VerticalAlignment.TOP);
} else if ("Center".equals(vertical)) {
dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
} else if ("Bottom".equals(vertical)) {
dataStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);
} else if ("JUSTIFY".equals(vertical)) {
dataStyle.setVerticalAlignment(VerticalAlignment.JUSTIFY);
} else {
dataStyle.setVerticalAlignment(VerticalAlignment.DISTRIBUTED);
}
}
String wrapText = style.getAlignment().getWrapText();
if (!ObjectUtils.isEmpty(wrapText)) {
dataStyle.setWrapText(true);
}
}
}
private static void setCellColor(Style style, CellStyle dataStyle) {
if (style != null && style.getInterior() != null) {
String color = style.getInterior().getColor();
if (color == null) {
color = "#FFFFFF";
}
Integer[] rgb = ColorUtil.hex2Rgb(color);
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFPalette palette = hssfWorkbook.getCustomPalette();
HSSFColor paletteColor = palette.findSimilarColor(rgb[0], rgb[1], rgb[2]);
dataStyle.setFillForegroundColor(paletteColor.getIndex());
dataStyle.setFillBackgroundColor(paletteColor.getIndex());
if ("Solid".equals(style.getInterior().getPattern())) {
dataStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
}
}
}
private static int getCellRanges(int createRowIndex, List<CellRangeAddressEntity> cellRangeAddresses, int startIndex, Cell cellInfo, Style style) {
if (cellInfo.getMergeAcross() != null || cellInfo.getMergeDown() != null) {
CellRangeAddress cellRangeAddress = null;
int length;
int i;
if (cellInfo.getMergeAcross() != null && cellInfo.getMergeDown() != null) {
length = startIndex;
if (cellInfo.getMergeAcross() != 0) {
length = startIndex + cellInfo.getMergeAcross();
}
i = createRowIndex;
if (cellInfo.getMergeDown() != 0) {
i = createRowIndex + cellInfo.getMergeDown();
}
cellRangeAddress = new CellRangeAddress(createRowIndex, i, (short)startIndex, (short)length);
} else if (cellInfo.getMergeAcross() != null && cellInfo.getMergeDown() == null) {
if (cellInfo.getMergeAcross() != 0) {
length = startIndex + cellInfo.getMergeAcross();
cellRangeAddress = new CellRangeAddress(createRowIndex, createRowIndex, (short)startIndex, (short)length);
}
} else if (cellInfo.getMergeDown() != null && cellInfo.getMergeAcross() == null && cellInfo.getMergeDown() != 0) {
length = createRowIndex + cellInfo.getMergeDown();
cellRangeAddress = new CellRangeAddress(createRowIndex, length, (short)startIndex, (short)startIndex);
}
if (cellInfo.getMergeAcross() != null) {
length = cellInfo.getMergeAcross();
for(i = 0; i < length; ++i) {
++startIndex;
}
}
CellRangeAddressEntity cellRangeAddressEntity = new CellRangeAddressEntity();
cellRangeAddressEntity.setCellRangeAddress(cellRangeAddress);
if (style != null && style.getBorders() != null) {
cellRangeAddressEntity.setBorders(style.getBorders());
}
cellRangeAddresses.add(cellRangeAddressEntity);
}
return startIndex;
}
private static void setValue(XSSFWorkbook wb, Cell cellInfo, XSSFCell cell, Style style, CellStyle dataStyle) {
if (cellInfo.getData() != null) {
XSSFFont font = wb.createFont();
String color;
Integer[] rgb;
HSSFWorkbook hssfWorkbook;
HSSFPalette palette;
HSSFColor paletteColor;
if (style != null && style.getFont() != null) {
color = style.getFont().getColor();
if (color == null) {
color = "#000000";
}
rgb = ColorUtil.hex2Rgb(color);
hssfWorkbook = new HSSFWorkbook();
palette = hssfWorkbook.getCustomPalette();
paletteColor = palette.findSimilarColor(rgb[0], rgb[1], rgb[2]);
font.setColor(paletteColor.getIndex());
}
if (!ObjectUtils.isEmpty(cellInfo.getData().getType()) && "Number".equals(cellInfo.getData().getType())) {
cell.setCellType(CellType.NUMERIC);
}
if (style != null && style.getFont().getBold() > 0) {
font.setBold(true);
}
if (style != null && !ObjectUtils.isEmpty(style.getFont().getFontName())) {
font.setFontName(style.getFont().getFontName());
}
if (style != null && style.getFont().getSize() > 0.0D) {
font.setFontHeightInPoints((short)((int)style.getFont().getSize()));
}
if (cellInfo.getData().getFont() != null) {
if (cellInfo.getData().getFont().getBold() > 0) {
font.setBold(true);
}
if ("Number".equals(cellInfo.getData().getType())) {
cell.setCellValue((double)Float.parseFloat(cellInfo.getData().getFont().getText()));
} else {
cell.setCellValue(cellInfo.getData().getFont().getText());
}
if (!ObjectUtils.isEmpty(cellInfo.getData().getFont().getCharSet())) {
font.setCharSet(Integer.valueOf(cellInfo.getData().getFont().getCharSet()));
}
} else if ("Number".equals(cellInfo.getData().getType())) {
if (!ObjectUtils.isEmpty(cellInfo.getData().getText())) {
cell.setCellValue((double)Float.parseFloat(cellInfo.getData().getText().replaceAll(",", "")));
}
} else {
cell.setCellValue(cellInfo.getData().getText());
}
if (style != null && style.getNumberFormat() != null) {
color = style.getFont().getColor();
if (color == null) {
color = "#000000";
}
rgb = ColorUtil.hex2Rgb(color);
hssfWorkbook = new HSSFWorkbook();
palette = hssfWorkbook.getCustomPalette();
paletteColor = palette.findSimilarColor(rgb[0], rgb[1], rgb[2]);
font.setColor(paletteColor.getIndex());
if ("0%".equals(style.getNumberFormat().getFormat())) {
XSSFDataFormat format = wb.createDataFormat();
dataStyle.setDataFormat(format.getFormat(style.getNumberFormat().getFormat()));
} else {
dataStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));
}
}
dataStyle.setFont(font);
}
}
private static void setValue(HSSFWorkbook wb, Cell cellInfo, HSSFCell cell, Style style, CellStyle dataStyle) {
if (cellInfo.getData() != null) {
HSSFFont font = wb.createFont();
String color;
Integer[] rgb;
HSSFWorkbook hssfWorkbook;
HSSFPalette palette;
HSSFColor paletteColor;
if (style != null && style.getFont() != null) {
color = style.getFont().getColor();
if (color == null) {
color = "#000000";
}
rgb = ColorUtil.hex2Rgb(color);
hssfWorkbook = new HSSFWorkbook();
palette = hssfWorkbook.getCustomPalette();
paletteColor = palette.findSimilarColor(rgb[0], rgb[1], rgb[2]);
font.setColor(paletteColor.getIndex());
}
if (!ObjectUtils.isEmpty(cellInfo.getData().getType()) && "Number".equals(cellInfo.getData().getType())) {
cell.setCellType(CellType.NUMERIC);
}
if (style != null && style.getFont().getBold() > 0) {
font.setBold(true);
}
if (style != null && !ObjectUtils.isEmpty(style.getFont().getFontName())) {
font.setFontName(style.getFont().getFontName());
}
if (style != null && style.getFont().getSize() > 0.0D) {
font.setFontHeightInPoints((short)((int)style.getFont().getSize()));
}
if (cellInfo.getData().getFont() != null) {
if (cellInfo.getData().getFont().getBold() > 0) {
font.setBold(true);
}
if ("Number".equals(cellInfo.getData().getType())) {
cell.setCellValue((double)Float.parseFloat(cellInfo.getData().getFont().getText()));
} else {
cell.setCellValue(cellInfo.getData().getFont().getText());
}
if (!ObjectUtils.isEmpty(cellInfo.getData().getFont().getCharSet())) {
font.setCharSet(Integer.valueOf(cellInfo.getData().getFont().getCharSet()));
}
} else if ("Number".equals(cellInfo.getData().getType())) {
if (!ObjectUtils.isEmpty(cellInfo.getData().getText())) {
cell.setCellValue((double)Float.parseFloat(cellInfo.getData().getText().replaceAll(",", "")));
}
} else {
cell.setCellValue(cellInfo.getData().getText());
}
if (style != null && style.getNumberFormat() != null) {
color = style.getFont().getColor();
if (color == null) {
color = "#000000";
}
rgb = ColorUtil.hex2Rgb(color);
hssfWorkbook = new HSSFWorkbook();
palette = hssfWorkbook.getCustomPalette();
paletteColor = palette.findSimilarColor(rgb[0], rgb[1], rgb[2]);
font.setColor(paletteColor.getIndex());
if ("0%".equals(style.getNumberFormat().getFormat())) {
HSSFDataFormat format = wb.createDataFormat();
dataStyle.setDataFormat(format.getFormat(style.getNumberFormat().getFormat()));
} else {
dataStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));
}
}
dataStyle.setFont(font);
}
}
}
package com.example.stu1.freemark;
import com.yongjiu.dto.freemarker.input.FreemarkerInput;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author yangcai
* @create 2022/7/1 16:43
*/
@RestController
public class UserController1 {
@GetMapping("/index")
public void index(HttpServletResponse response) {
try{
String fileName = URLEncoder.encode(" Test export ", "UTF-8");
Map<String,Object> resultMap= getList();
FreemarkerInput freemarkerInput = new FreemarkerInput();
freemarkerInput.setTemplateFilePath("/templates");
freemarkerInput.setTemplateName("test.ftl");
freemarkerInput.setXmlTempFile(System.getProperty("java.io.tmpdir"));
freemarkerInput.setFileName(fileName);
freemarkerInput.setDataMap(resultMap);
FreeMarkerTemplateUtil.exportImageExcelNew(response, freemarkerInput);
} catch (Exception e) {
e.printStackTrace();
}
}
Map<String,Object> getList(){
Map<String,Object> map = new HashMap<>();
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setAge(26);
user1.setEmail("[email protected]");
user1.setName(" zhang wuji ");
userList.add(user1);
User user2 = new User();
user2.setAge(27);
user2.setEmail("[email protected]");
user2.setName(" Xiaoyao Zi ");
userList.add(user2);
User user3 = new User();
user3.setAge(28);
user3.setEmail("[email protected]");
user3.setName(" Xiao feng ");
userList.add(user3);
map.put("userList",userList);
return map;
}
}
Generated at this time xlsx The document is real excel file , Can be office Normal opening

poi analysis excel file
public static Function<UploadExcelObject,List<Map<String, IndexDataPo>>> getExcelDataOne = uploadExcelObject->{
try(FileInputStream fileInputStream = new FileInputStream(uploadExcelObject.getFileUrl())) {
Workbook workbook = null;
if (uploadExcelObject.getFileUrl().endsWith(".xls")) {
try {
workbook = new HSSFWorkbook(fileInputStream);
} catch (OfficeXmlFileException e) {
try {
workbook = new XSSFWorkbook(fileInputStream);
} catch (Exception e1) {
log.error(e.getMessage());
}
} catch (IOException e) {
throw new CommonException("109",e.getMessage());
}
} else if (uploadExcelObject.getFileUrl().endsWith(".xlsx")) {
try {
workbook = new XSSFWorkbook(fileInputStream);
} catch (Exception e) {
e.printStackTrace();
throw new CommonException("110",e.getMessage());
}
}
try {
int sheetNo = workbook.getNumberOfSheets();
List<Map<String, IndexDataPo>> list = Lists.newArrayList();
log.info(String.format(" This document has %d How many pages ",sheetNo));
for(int i=0 ; i< sheetNo ;i++){
Sheet sheet = workbook.getSheetAt(0);
List<String> headerList = checkAndGetHeader(sheet,TemplateTypeEnum.ONE_DATE.getCode(),uploadExcelObject.getIndexCodeList());
for (int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {
XSSFRow row = (XSSFRow) sheet.getRow(j);
if(row!=null) {
if(isRowEmpty(row)){
continue;
}
IndexDataPo dto = new IndexDataPo();
for (int k = 0; k < sheet.getRow(1).getPhysicalNumberOfCells(); k++) {
String value = null;
Cell cell = row.getCell(k);
if(k==0){
if("".equals(cell.toString()) || cell.toString() == ""){
throw new CommonException("101"," No time entered ");
}
if(DateUtil.isCellDateFormatted(cell)){
dto.setDataDate(cell.getDateCellValue());
}
}else{
Map<String, IndexDataPo> map = Maps.newHashMap();
if(cell != null){
value = getCellValue(cell);
}
if(StringUtils.isEmpty(value)){
dto.setDataValue(null);
}else{
dto.setDataValue(Double.valueOf(value));
}
dto.setIndexCode(headerList.get(k));
map.put(DateUtils.getDateLong(dto.getDataDate()), dto);
list.add(map);
dto = new IndexDataPo(dto.getDataDate());
}
}
}
}
}
return list;
} catch (Exception e) {
log.error(e.getMessage(),e);
throw new CommonException(" analysis excel error :"," analysis excel error "+e.getMessage());
}
} catch (IOException e) {
log.error(e.getMessage(),e);
}
return null;
};
边栏推荐
猜你喜欢

Virtual lab basic experiment tutorial -7 Polarization (1)

Asemi rectifier bridge umb10f parameters, umb10f specifications, umb10f package

Modbus协议通信异常

Keras' deep learning practice -- gender classification based on vgg19 model

finally详解

Alibaba cloud sub account - Permission Policy - full control permission granted to an account and an OSS bucket

Rk1126 platform project summary

智能水电表能耗监测云平台

自定义一个loading指令

freemarker+poi实现动态生成excel文件及解析excel文件
随机推荐
【网络是怎么连接的】第四章 探索接入网和网络运营商
977.有序数组的平方
切换变换的时候记得使用三元表达式
蓝牙技术|物联网的可穿戴设备新工作模式,蓝牙BLE助力新工作模式
应广单片机开发 工规 PMC131 带AD芯片检测电池电压单片机SOP8/14
【Zuul】com. netflix. zuul. exception. ZuulException: Hystrix Readed time out
Keras深度学习实战——基于VGG19模型实现性别分类
Redisson 高性能 Redis 分布式锁源码分析
怎么可以省去大量的switch语句,省去switch语句
Aloam code reading and summary
[how is the network connected] Chapter 4 explores access networks and network operators
Taiwan Feiling fm8pb513b MCU provides MCU program development product design
freemarker+poi实现动态生成excel文件及解析excel文件
JDBC
567.字符串中的排列
Typescript
PMS132B单片机TWS数码管蓝牙充电仓方案开发
Finally detailed explanation
2 juillet: BitTorrent est sorti; L'acquisition du système commercial linspire; Sony Deployment PlayStation now
uva1169