qa-prevention-gwj/src/main/java/com/zcloud/util/HiddenExcelImgView.java

194 lines
7.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.zcloud.util;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.introspect.AnnotationMap;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
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.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.document.AbstractXlsView;
import com.zcloud.entity.PageData;
/**
* 说明导出到EXCEL
* 作者luoxiaobao
* 官网www.qdkjchina.com
*/
public class HiddenExcelImgView extends AbstractXlsView{
@Value("${http.file.url}")
private String fileUrl;
@Override
protected void buildExcelDocument(Map<String, Object> model,
Workbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
String proPath = PathUtil.getProjectpath();
String beji = fileUrl;
//beji =beji.replaceAll("\\\\", "/");
Date date = new Date();
String filename = DateUtil.date2Str(date, "yyyyMMddHHmmss");
HSSFSheet sheet;
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls");
HSSFWorkbook book = (HSSFWorkbook) workbook;
sheet = book.createSheet("sheet1");
List<String> titles = (List<String>) model.get("titles");
int len = titles.size();
HSSFCellStyle headerStyle = book.createCellStyle(); //标题样式
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
HSSFFont headerFont = book.createFont(); //标题字体
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short)11);
headerStyle.setFont(headerFont);
short height=25*20;
HSSFRow row = sheet.createRow(0);
if(len>250) {
len = 250;
}
for(int i=0; i<len; i++){ //设置标题
String title = titles.get(i);
row.setRowStyle(headerStyle);
if(title.length()>250) {
row.createCell(i).setCellValue(title.substring(0, 250));
}else {
row.createCell(i).setCellValue(title);
}
}
sheet.getRow(0).setHeight(height);
HSSFCellStyle contentStyle = book.createCellStyle(); //内容样式
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
contentStyle.setAlignment(HorizontalAlignment.CENTER);
List<PageData> varList = (List<PageData>) model.get("varList");
int varCount = varList.size();
for(int i=0; i<varCount; i++){
PageData vpd = varList.get(i);
HSSFRow rows = sheet.createRow(i+1);
for(int j=0;j<len;j++){
String valKey = "var"+(j+1);
String imgKey = "img" +(j+1);
if(vpd.containsKey(valKey)) {
String varstr = vpd.getString(valKey) != null ? vpd.getString("var"+(j+1)) : "";
rows.setRowStyle(contentStyle);
rows.createCell(j).setCellValue(varstr);
}
if(vpd.containsKey(imgKey)) {
String varstr = vpd.getString(imgKey) != null ? vpd.getString("img"+(j+1)) : "";
if(Tools.isEmpty(varstr)) {
continue;
}
try {
URL url = new URL(beji + varstr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();
byte[] data = readInputStream(inStream);
byte[] compressPicForScale = compressPicForScale(data, 100);
HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 0, 0,(short) (j), (i+1), (short) (j+1), (i+2));
patriarch.createPicture(anchor1, book.addPicture(compressPicForScale, HSSFWorkbook.PICTURE_TYPE_JPEG));
}catch (Exception e) {
System.out.println("未找到图片");
e.printStackTrace();
}
// BufferedImage bufferImg = null;//图片一
// ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();//
// File file=new File(beji+varstr);
// if(file.exists()) {//https://wwag.qhdsafety.com/file//uploadFiles/yhtp/07bd077457ec4da7bd6ec2219984079c/20220126/545463a3effe4a3d9d50dc701c69cc01.png
// bufferImg = ImageIO.read(file);
// ImageIO.write(bufferImg, "jpg", byteArrayOut);
// HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 0, 0,(short) (j), (i+1), (short) (j+1), (i+2));
// patriarch.createPicture(anchor1, book.addPicture(byteArrayOut
// .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
// }
}
}
}
}
private static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while( (len=inStream.read(buffer)) != -1 ){
//用输出流往buffer里写入数据中间参数代表从哪个位置开始读len代表读取的长度
outStream.write(buffer, 0, len);
}
//关闭输入流
inStream.close();
//把outStream里的数据写入内存
return outStream.toByteArray();
}
private static final Integer ZERO = 0;
private static final Integer ONE_ZERO_TWO_FOUR = 1024;
private static final Integer NINE_ZERO_ZERO = 900;
private static final Integer THREE_TWO_SEVEN_FIVE = 3275;
private static final Integer TWO_ZERO_FOUR_SEVEN = 2047;
private static final Double ZERO_EIGHT_FIVE = 0.85;
private static final Double ZERO_SIX = 0.6;
private static final Double ZERO_FOUR_FOUR = 0.44;
private static final Double ZERO_FOUR = 0.4;
public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
if (imageBytes == null || imageBytes.length <= ZERO || imageBytes.length < desFileSize * ONE_ZERO_TWO_FOUR) {
return imageBytes;
}
double accuracy = 0.5d;
try {
while (imageBytes.length > desFileSize * ONE_ZERO_TWO_FOUR) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
Thumbnails.of(inputStream)
.scale(accuracy)
.outputQuality(accuracy)
.toOutputStream(outputStream);
imageBytes = outputStream.toByteArray();
}
System.out.println("图片原大小={}kb | 压缩后大小={}kb");
// logger.info("图片原大小={}kb | 压缩后大小={}kb",
// srcSize / ONE_ZERO_TWO_FOUR, imageBytes.length / ONE_ZERO_TWO_FOUR);
} catch (Exception e) {
// logger.error("【图片压缩】msg=图片压缩失败!", e);
}
return imageBytes;
}
}