1.poi版本
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>
2.水印工具類
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.imageio.ImageIO;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* 新增水印
* 只支持XSSFWorkbook
* .xlsx
*
* @author archie
* @date 2024-02-02
*/
@Slf4j
public class ExcelWaterMark {
public static ByteArrayOutputStream createWaterMark(String content) {
int width = 200;
int height = 150;
// 獲取bufferedImage對象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
String fontType = "微軟雅黑";
int fontStyle = Font.BOLD;
int fontSize = 20;
Font font = new Font(fontType, fontStyle, fontSize);
// 獲取Graphics2d對象
Graphics2D g2d = image.createGraphics();
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
//設(shè)置字體顏色和透明度,最后一個參數(shù)為透明度 設(shè)置字體
g2d.setColor(new Color(0, 0, 0, 30));
g2d.setStroke(new BasicStroke(1));
g2d.setFont(font);
// 設(shè)置字體類型 加粗 大小設(shè)置傾斜度
g2d.rotate(-0.5, (double) image.getWidth() / 2, (double) image.getHeight() / 2);
FontRenderContext context = g2d.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(content, context);
double x = (width - bounds.getWidth()) / 2;
double y = (height - bounds.getHeight()) / 2;
double ascent = -bounds.getY();
double baseY = y + ascent;
// 寫入水印文字原定高度過小,所以累計寫水印篙挽,增加高度
g2d.drawString(content, (int) x, (int) baseY);
// 設(shè)置透明度
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// 釋放對象
g2d.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", os);
} catch (IOException e) {
log.error("寫入水印圖片失敗", e);
throw new RuntimeException(e);
}
return os;
}
/**
* 為Excel打上水印工具函數(shù)
*
* @param sheet excel sheet
* @param bytes 水印圖片字節(jié)數(shù)組
*/
public static void putWaterRemarkToExcel(XSSFSheet sheet, byte[] bytes) {
//add relation from sheet to the picture data
XSSFWorkbook workbook = sheet.getWorkbook();
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
String rID = sheet.addRelation(null, XSSFRelation.IMAGES, workbook.getAllPictures().get(pictureIdx))
.getRelationship().getId();
//set background picture to sheet
sheet.getCTWorksheet().addNewPicture().setId(rID);
}
}
Excel導出工具類
import org.apache.commons.lang3.StringUtils;
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.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* excel導出工具
*
* @author archie
*/
public class ExcelsXlsxUtil {
private static final Logger logger = LoggerFactory.getLogger(ExcelsXlsxUtil.class);
/**
* 時間格式
*/
private static final String TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* 默認列的寬度
*/
private static final int COLUMN_WIDTH = 24;
/**
* 表頭字體大小
*/
private static final int TITLE_FONT_SIZE = 11;
/**
* 表頭單元格
**/
private static final int TITLE_CELL = 0;
/**
* 內(nèi)容單元格
**/
private static final int CONTENT_CELL = 1;
/**
* 每個sheeet的最大數(shù)據(jù)數(shù)量
*/
private static final int MAX_LENGTH = 60000;
/**
* 導出
* 2003版本的xls
*
* @param title 表格標題名,文件名
* @param headers 表格頭部標題中文集合
* @param headerZhWords 表格頭部標題的字段名
* @param dataSet 需要顯示的數(shù)據(jù)集合
*/
public static <T> void exportExcel(String title, String[] headers, String[] headerZhWords, Collection<T> dataSet,
String waterMaker,
HttpServletResponse response) throws UnsupportedEncodingException {
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", String.format("attachment;filename=%s.xlsx",
URLEncoder.encode(title, "UTF-8")));
//水印文字
byte[] wYBytes = new byte[0];
if (!StringUtils.isEmpty(waterMaker)) {
wYBytes = ExcelWaterMark.createWaterMark(waterMaker).toByteArray();
}
try (XSSFWorkbook workbook = new XSSFWorkbook();
ServletOutputStream out = response.getOutputStream()) {
int pageNum = 1;
int dataLength = dataSet.size();
List<T> dataAll = new ArrayList<>(dataSet);
List<T> dataPage;
//分sheet處理 每個sheet數(shù)據(jù)條數(shù)為MAX_LENGTH
while (dataLength >= 0) {
if (dataLength > MAX_LENGTH) {
dataPage = dataAll.subList((pageNum - 1) * MAX_LENGTH, pageNum * MAX_LENGTH);
} else {
dataPage = dataAll.subList((pageNum - 1) * MAX_LENGTH, dataAll.size());
}
// 生成一個sheet
XSSFSheet sheet = workbook.createSheet(String.format("%s -%s-", title, pageNum));
dataLength -= MAX_LENGTH;
pageNum++;
// 設(shè)置表格默認列寬度
sheet.setDefaultColumnWidth(COLUMN_WIDTH);
// 生成標題樣式
CellStyle titleStyle = setCellStyle(workbook, TITLE_CELL);
// 產(chǎn)生表格標題行
XSSFRow row = sheet.createRow(0);
XSSFCell cellHeader;
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i);
cellHeader.setCellStyle(titleStyle);
cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
}
//填充內(nèi)容
fillContent(headerZhWords, dataPage, workbook, sheet, 0);
if (wYBytes.length > 0) {
ExcelWaterMark.putWaterRemarkToExcel(sheet, wYBytes);
}
}
workbook.write(out);
} catch (IOException e) {
logger.error("excel生成錯誤", e);
}
}
/**
* 設(shè)置樣式
**/
private static CellStyle setCellStyle(XSSFWorkbook workbook, int cellType) {
CellStyle style = null;
//邊框
BorderStyle borderStyle = BorderStyle.THIN;
short borderColor = HSSFColor.HSSFColorPredefined.BLACK.getIndex();
if (cellType == TITLE_CELL) {
style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(borderStyle);
style.setBorderLeft(borderStyle);
style.setBorderRight(borderStyle);
style.setBorderTop(borderStyle);
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
style.setTopBorderColor(borderColor);
style.setLeftBorderColor(borderColor);
style.setRightBorderColor(borderColor);
style.setBottomBorderColor(borderColor);
//垂直居中
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
style.setVerticalAlignment(VerticalAlignment.CENTER);
//自動換行
style.setWrapText(false);
// 生成標題字體
Font font = workbook.createFont();
font.setBold(true);
font.setFontName("宋體");
font.setColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
font.setFontHeightInPoints((short) TITLE_FONT_SIZE);
// 把字體應用到當前的樣式
style.setFont(font);
} else if (cellType == CONTENT_CELL) {
style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.AUTOMATIC.getIndex());
style.setFillPattern(FillPatternType.NO_FILL);
style.setBorderBottom(borderStyle);
style.setBorderLeft(borderStyle);
style.setBorderRight(borderStyle);
style.setBorderTop(borderStyle);
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
style.setVerticalAlignment(VerticalAlignment.CENTER);
//設(shè)置自動換行
style.setWrapText(false);
// 生成內(nèi)容字體
Font font = workbook.createFont();
font.setBold(false);
style.setFont(font);
}
return style;
}
/**
* 填充sheet內(nèi)容
*
* @param headerWords 填充數(shù)據(jù)的字段
* @param dataSet 數(shù)據(jù)集
* @param workbook 工作上下文
* @param sheet sheet
* @param contentStartIndex 從第contentStartIndex+1行開始填充數(shù)據(jù)
*/
private static <T> void fillContent(String[] headerWords, Collection<T> dataSet, XSSFWorkbook workbook, XSSFSheet sheet,
Integer contentStartIndex) {
//內(nèi)容樣式
CellStyle contentStyle = setCellStyle(workbook, CONTENT_CELL);
SimpleDateFormat sdf = new SimpleDateFormat(TIME_PATTERN);
//字段名
String fieldName;
//get方法名稱
String getMethodName;
//單元格
XSSFCell cell;
Method getMethod;
Object value = "";
XSSFRow row;
contentStartIndex = contentStartIndex == null ? 0 : contentStartIndex;
T t;
int index = 0;
Iterator<T> it = dataSet.iterator();
while (it.hasNext()) {
index++;
row = sheet.createRow(index + contentStartIndex);
t = it.next();
for (int i = 0; i < headerWords.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(contentStyle);
fieldName = headerWords[i];
if (t instanceof Map) {
//Map類型
value = ((Map<?, ?>) t).get(fieldName);
} else {
getMethodName = getBeanMethodName(fieldName);
//Bean類
try {
getMethod = t.getClass().getMethod(getMethodName);
value = getMethod.invoke(t);
} catch (SecurityException | NoSuchMethodException | IllegalAccessException |
InvocationTargetException e) {
logger.error("excel生成錯誤", e);
}
}
if (null == value) {
cell.setCellValue("");
} else if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float || value instanceof Double) {
cell.setCellValue(String.valueOf(value));
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
} else if (value instanceof Date) {
cell.setCellValue(sdf.format((Date) value));
} else {
cell.setCellValue(String.valueOf(value));
}
}
}
}
/**
* 獲取bean的獲取值的方法
*
* @param fieldName
* @return
*/
private static String getBeanMethodName(String fieldName) {
String cacheName = CommonConstant.CachePre.METHOD + fieldName;
String methodName = String.valueOf(CommonConstant.BaseCache.COMMON_CACHE.get(cacheName));
if (CommonConstant.BaseConstant.NULL.equals(methodName)) {
methodName = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
CommonConstant.BaseCache.COMMON_CACHE.put(cacheName, methodName);
}
return methodName;
}
}