Commit 208f9517 authored by licc's avatar licc

二维码导出

parent c5bd5c0e
......@@ -140,21 +140,21 @@
<artifactId>shiro-spring</artifactId>
</dependency>
<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.apache.poi</groupId>-->
<!-- <artifactId>poi</artifactId>-->
<!-- <version>3.9</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.poi</groupId>-->
<!-- <artifactId>poi-ooxml</artifactId>-->
<!-- <version>3.9</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.poi</groupId>-->
<!-- <artifactId>poi-ooxml-schemas</artifactId>-->
<!-- <version>3.9</version>-->
<!-- </dependency>-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
......
package cn.wisenergy.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ExcelUtils {
private static final String EXTENSION_XLS = "xls";
private static final String EXTENSION_XLSX = "xlsx";
/**
* 判断EXCEL版本
*
* @param in
* @param filename
* @return
* @throws IOException
*/
public static Workbook getWorkbook(InputStream in, String filename) throws IOException {
Workbook wb = null;
if (filename.endsWith(EXTENSION_XLS)) {
wb = new HSSFWorkbook(in);//Excel 2003
} else if (filename.endsWith(EXTENSION_XLSX)) {
wb = new XSSFWorkbook(in);//Excel 2007
}
return wb;
}
/**
* 文件校验是否是excel
*
* @param filePath
* @throws FileNotFoundException
* @throws FileFormatException
*/
public static void preReadCheck(String fileName) throws FileNotFoundException,
FileFormatException {
// 常规检查
if (StringUtils.isBlank(fileName)) {
throw new FileNotFoundException("传入的文件不存在:" + fileName);
}
if (!fileName.endsWith(EXTENSION_XLS) && !fileName.endsWith(EXTENSION_XLSX)) {
throw new FileFormatException("传入的文件不是excel");
}
}
/**
* 读取EXCEL
*
* @param filePath
* @throws FileNotFoundException
* @throws FileFormatException
*/
public static List<List<String>> readExcel(MultipartFile file) throws FileNotFoundException, FileFormatException {
// 检查
preReadCheck(file.getOriginalFilename());
// 获取workbook对象
Workbook workbook = null;
/*InputStream is = new FileInputStream(filePath);*/
List<List<String>> result = new ArrayList<List<String>>();
try {
workbook = getWorkbook(file.getInputStream(), file.getOriginalFilename());
// workbook = WorkbookFactory.create(is);
int sheetCount = workbook.getNumberOfSheets(); //Sheet的数量
// 读文件 一个sheet一个sheet地读取
for (int numSheet = 0; numSheet < sheetCount; numSheet++) {
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
int firstRowIndex = sheet.getFirstRowNum();
int lastRowIndex = sheet.getLastRowNum();
if (firstRowIndex != lastRowIndex && lastRowIndex != 0) {
// 读取数据行
for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
Row currentRow = sheet.getRow(rowIndex);// 当前行
int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
List<String> rowList = new ArrayList<String>();
for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
Cell currentCell = currentRow.getCell(columnIndex);// 当前单元格
String currentCellValue = getCellValue(currentCell, true);// 当前单元格的值
rowList.add(currentCellValue);
}
//行为空的不读
Boolean flag = false;
for (String str : rowList) {
if (!StringUtils.isBlank(str)) {
flag = true;
break;
}
}
if (flag) {
result.add(rowList);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return result;
}
public static List<List<String>> readInlandCompare(String filePath, Integer startSheet, Integer endSheet) throws FileNotFoundException, FileFormatException {
// 检查
preReadCheck(filePath);
// 获取workbook对象
Workbook workbook = null;
InputStream is = new FileInputStream(filePath);
List<List<String>> result = new ArrayList<List<String>>();
try {
workbook = getWorkbook(is, filePath);
// workbook = WorkbookFactory.create(is);
int sheetCount = workbook.getNumberOfSheets(); //Sheet的数量
// 读文件 一个sheet一个sheet地读取
for (int numSheet = startSheet; numSheet < endSheet; numSheet++) {
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
int firstRowIndex = sheet.getFirstRowNum();
int lastRowIndex = sheet.getLastRowNum();
if (firstRowIndex != lastRowIndex && lastRowIndex != 0) {
// 读取数据行
for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
Row currentRow = sheet.getRow(rowIndex);// 当前行
int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
List<String> rowList = new ArrayList<String>();
for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
Cell currentCell = currentRow.getCell(columnIndex);// 当前单元格
String currentCellValue = getCellValue(currentCell, true);// 当前单元格的值
rowList.add(currentCellValue);
}
//行为空的不读
Boolean flag = false;
for (String str : rowList) {
if (!StringUtils.isBlank(str)) {
flag = true;
break;
}
}
if (flag) {
result.add(rowList);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return result;
}
/**
* 取单元格的值
*
* @param cell 单元格对象
* @param treatAsStr 为true时,当做文本来取值 (取到的是文本,不会把“1”取成“1.0”)
* @return
*/
public static String getCellValue(Cell cell, boolean treatAsStr) {
if (cell == null) {
return "";
}
/* if (treatAsStr) {
// 虽然excel中设置的都是文本,但是数字文本还被读错,如“1”取成“1.0”
// 加上下面这句,临时把它当做文本来读取
cell.setCellType(Cell.CELL_TYPE_STRING);
}*/
//SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
String cellValue = null;
int cellType = cell.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_STRING: // 文本
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC: // 数字、日期
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
SimpleDateFormat sdf = null;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm:ss");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = cell.getDateCellValue();
return sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
return sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 单元格设置成常规
if (temp.equals("General")) {
format.applyPattern("#");
}
return format.format(value);
}
case Cell.CELL_TYPE_BOOLEAN: // 布尔型
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK: // 空白
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_ERROR: // 错误
cellValue = "错误";
break;
case Cell.CELL_TYPE_FORMULA: // 公式
/* try {
cellValue = cell.getStringCellValue();
} catch (IllegalStateException e) {
cellValue = String.valueOf(cell.getNumericCellValue());
}*/
try {
cellValue = String.valueOf(cell.getNumericCellValue());
} catch (IllegalStateException e) {
cellValue = String.valueOf(cell.getRichStringCellValue());
}
break;
default:
cellValue = "错误";
}
return cellValue;
}
}
//package cn.wisenergy.common.utils;
//
//
//import org.apache.commons.lang3.StringUtils;
//import org.apache.poi.hssf.usermodel.HSSFDataFormat;
//import org.apache.poi.hssf.usermodel.HSSFDateUtil;
//import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//import org.apache.poi.ss.usermodel.*;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
//import org.springframework.web.multipart.MultipartFile;
//
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.IOException;
//import java.io.InputStream;
//import java.text.DecimalFormat;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//
//public class ExcelUtils {
//
//
// private static final String EXTENSION_XLS = "xls";
// private static final String EXTENSION_XLSX = "xlsx";
//
//
// /**
// * 判断EXCEL版本
// *
// * @param in
// * @param filename
// * @return
// * @throws IOException
// */
// public static Workbook getWorkbook(InputStream in, String filename) throws IOException {
// Workbook wb = null;
// if (filename.endsWith(EXTENSION_XLS)) {
// wb = new HSSFWorkbook(in);//Excel 2003
// } else if (filename.endsWith(EXTENSION_XLSX)) {
// wb = new XSSFWorkbook(in);//Excel 2007
// }
// return wb;
// }
//
//
// /**
// * 文件校验是否是excel
// *
// * @param filePath
// * @throws FileNotFoundException
// * @throws FileFormatException
// */
// public static void preReadCheck(String fileName) throws FileNotFoundException,
// FileFormatException {
// // 常规检查
// if (StringUtils.isBlank(fileName)) {
// throw new FileNotFoundException("传入的文件不存在:" + fileName);
// }
//
// if (!fileName.endsWith(EXTENSION_XLS) && !fileName.endsWith(EXTENSION_XLSX)) {
// throw new FileFormatException("传入的文件不是excel");
// }
// }
//
//
// /**
// * 读取EXCEL
// *
// * @param filePath
// * @throws FileNotFoundException
// * @throws FileFormatException
// */
// public static List<List<String>> readExcel(MultipartFile file) throws FileNotFoundException, FileFormatException {
// // 检查
// preReadCheck(file.getOriginalFilename());
// // 获取workbook对象
// Workbook workbook = null;
// /*InputStream is = new FileInputStream(filePath);*/
// List<List<String>> result = new ArrayList<List<String>>();
// try {
// workbook = getWorkbook(file.getInputStream(), file.getOriginalFilename());
// // workbook = WorkbookFactory.create(is);
//
// int sheetCount = workbook.getNumberOfSheets(); //Sheet的数量
// // 读文件 一个sheet一个sheet地读取
// for (int numSheet = 0; numSheet < sheetCount; numSheet++) {
// Sheet sheet = workbook.getSheetAt(numSheet);
// if (sheet == null) {
// continue;
// }
//
// int firstRowIndex = sheet.getFirstRowNum();
// int lastRowIndex = sheet.getLastRowNum();
//
// if (firstRowIndex != lastRowIndex && lastRowIndex != 0) {
//
// // 读取数据行
// for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
// Row currentRow = sheet.getRow(rowIndex);// 当前行
// int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
// int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
// List<String> rowList = new ArrayList<String>();
// for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
// Cell currentCell = currentRow.getCell(columnIndex);// 当前单元格
//
// String currentCellValue = getCellValue(currentCell, true);// 当前单元格的值
// rowList.add(currentCellValue);
// }
//
// //行为空的不读
// Boolean flag = false;
// for (String str : rowList) {
// if (!StringUtils.isBlank(str)) {
// flag = true;
// break;
// }
// }
// if (flag) {
// result.add(rowList);
// }
// }
// }
//
// }
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// }
// return result;
// }
//
// public static List<List<String>> readInlandCompare(String filePath, Integer startSheet, Integer endSheet) throws FileNotFoundException, FileFormatException {
// // 检查
// preReadCheck(filePath);
// // 获取workbook对象
// Workbook workbook = null;
// InputStream is = new FileInputStream(filePath);
// List<List<String>> result = new ArrayList<List<String>>();
// try {
// workbook = getWorkbook(is, filePath);
// // workbook = WorkbookFactory.create(is);
//
// int sheetCount = workbook.getNumberOfSheets(); //Sheet的数量
// // 读文件 一个sheet一个sheet地读取
// for (int numSheet = startSheet; numSheet < endSheet; numSheet++) {
// Sheet sheet = workbook.getSheetAt(numSheet);
// if (sheet == null) {
// continue;
// }
//
// int firstRowIndex = sheet.getFirstRowNum();
// int lastRowIndex = sheet.getLastRowNum();
//
// if (firstRowIndex != lastRowIndex && lastRowIndex != 0) {
//
// // 读取数据行
// for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
// Row currentRow = sheet.getRow(rowIndex);// 当前行
// int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
// int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
// List<String> rowList = new ArrayList<String>();
// for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
// Cell currentCell = currentRow.getCell(columnIndex);// 当前单元格
//
// String currentCellValue = getCellValue(currentCell, true);// 当前单元格的值
// rowList.add(currentCellValue);
// }
// //行为空的不读
// Boolean flag = false;
// for (String str : rowList) {
// if (!StringUtils.isBlank(str)) {
// flag = true;
// break;
// }
// }
// if (flag) {
// result.add(rowList);
// }
// }
// }
//
// }
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// }
// return result;
// }
//
// /**
// * 取单元格的值
// *
// * @param cell 单元格对象
// * @param treatAsStr 为true时,当做文本来取值 (取到的是文本,不会把“1”取成“1.0”)
// * @return
// */
// public static String getCellValue(Cell cell, boolean treatAsStr) {
// if (cell == null) {
// return "";
// }
//
// /* if (treatAsStr) {
// // 虽然excel中设置的都是文本,但是数字文本还被读错,如“1”取成“1.0”
// // 加上下面这句,临时把它当做文本来读取
// cell.setCellType(Cell.CELL_TYPE_STRING);
// }*/
// //SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
//
// String cellValue = null;
// int cellType = cell.getCellType();
// switch (cellType) {
// case Cell.CELL_TYPE_STRING: // 文本
// cellValue = cell.getStringCellValue();
// break;
// case Cell.CELL_TYPE_NUMERIC: // 数字、日期
// if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
// SimpleDateFormat sdf = null;
// if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
// .getBuiltinFormat("h:mm")) {
// sdf = new SimpleDateFormat("HH:mm:ss");
// } else {// 日期
// sdf = new SimpleDateFormat("yyyy-MM-dd");
// }
// Date date = cell.getDateCellValue();
// return sdf.format(date);
// } else if (cell.getCellStyle().getDataFormat() == 58) {
// // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// double value = cell.getNumericCellValue();
// Date date = org.apache.poi.ss.usermodel.DateUtil
// .getJavaDate(value);
// return sdf.format(date);
// } else {
// double value = cell.getNumericCellValue();
// CellStyle style = cell.getCellStyle();
// DecimalFormat format = new DecimalFormat();
// String temp = style.getDataFormatString();
// // 单元格设置成常规
// if (temp.equals("General")) {
// format.applyPattern("#");
// }
// return format.format(value);
// }
//
// case Cell.CELL_TYPE_BOOLEAN: // 布尔型
// cellValue = String.valueOf(cell.getBooleanCellValue());
// break;
// case Cell.CELL_TYPE_BLANK: // 空白
// cellValue = cell.getStringCellValue();
// break;
// case Cell.CELL_TYPE_ERROR: // 错误
// cellValue = "错误";
// break;
// case Cell.CELL_TYPE_FORMULA: // 公式
// /* try {
// cellValue = cell.getStringCellValue();
// } catch (IllegalStateException e) {
// cellValue = String.valueOf(cell.getNumericCellValue());
// }*/
// try {
// cellValue = String.valueOf(cell.getNumericCellValue());
// } catch (IllegalStateException e) {
// cellValue = String.valueOf(cell.getRichStringCellValue());
// }
// break;
// default:
// cellValue = "错误";
// }
// return cellValue;
// }
//
//
//}
package cn.wisenergy.common.utils.exportView.view;
import cn.wisenergy.common.utils.FileUtil;
import cn.wisenergy.common.utils.exportView.convert.Convert;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.document.AbstractXlsxView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* excel视图
*/
public class ExcelView extends AbstractXlsxView {
/**
* 日志类
*/
private Logger log = LoggerFactory.getLogger(this.getClass());
/**
* 文件名称
*/
private String filename;
/**
* 表名称
*/
private String sheetName;
/**
* 属性
*/
private String[] properties;
/**
* 标题
*/
private String[] titles;
/**
* 图片属性集合
*/
private String[] pictures;
/**
* 列宽
*/
private Integer[] widths;
/**
* 表体高度
*/
private Float bodyHeight;
/**
* 数据
*/
private Collection<?> data;
/**
* 附加内容
*/
private String[] contents;
/**
* 数据转换map
*/
private Map<String, Convert> convertMap = new HashMap<String, Convert>();
/**
* @param filename
* 文件名称
* @param sheetName
* 表名称
* @param properties
* 属性
* @param titles
* 标题
* @param widths
* 列宽
* @param data
* 数据
* @param contents
* 附加内容
* @param convertMap
* 数据转化map
*/
public ExcelView(String filename, String sheetName, String[] properties,
String[] titles, Integer[] widths, Collection<?> data,
String[] contents, Map<String, Convert> convertMap) {
this.filename = filename;
this.sheetName = sheetName;
this.properties = properties;
this.titles = titles;
this.widths = widths;
this.data = data;
this.contents = contents;
this.convertMap = MapUtils.isEmpty(convertMap) ? this.convertMap
: convertMap;
}
/**
* @param filename
* 文件名称
* @param sheetName
* 表名称
* @param properties
* 属性
* @param titles
* 标题
* @param pictures
* 图片属性
* @param widths
* 列宽
* @param bodyHeight
* 表体高度
* @param data
* 数据
* @param contents
* 附加内容
* @param convertMap
* 数据转化map
*/
public ExcelView(String filename, String sheetName, String[] properties,
String[] titles, String[] pictures, Integer[] widths,
Float bodyHeight, Collection<?> data, String[] contents,
Map<String, Convert> convertMap) {
this.filename = filename;
this.sheetName = sheetName;
this.properties = properties;
this.titles = titles;
this.pictures = pictures;
this.widths = widths;
this.bodyHeight = bodyHeight;
this.data = data;
this.contents = contents;
this.convertMap = MapUtils.isEmpty(convertMap) ? this.convertMap
: convertMap;
}
/**
* @param properties
* 属性
* @param titles
* 标题
* @param data
* 数据
* @param contents
* 附加内容
*/
public ExcelView(String filename, String[] properties, String[] titles,
Collection<?> data, String[] contents,
Map<String, Convert> convertMap) {
this.filename = filename;
this.properties = properties;
this.titles = titles;
this.data = data;
this.contents = contents;
this.convertMap = MapUtils.isEmpty(convertMap) ? this.convertMap
: convertMap;
}
/**
* @param properties
* 属性
* @param titles
* 标题
* @param data
* 数据
*/
public ExcelView(String filename, String[] properties, String[] titles,
Collection<?> data, Map<String, Convert> convertMap) {
this.filename = filename;
this.properties = properties;
this.titles = titles;
this.data = data;
this.convertMap = MapUtils.isEmpty(convertMap) ? this.convertMap
: convertMap;
}
/**
* @param properties
* 属性
* @param data
* 数据
*/
public ExcelView(String[] properties, Collection<?> data) {
this.properties = properties;
this.data = data;
}
@SuppressWarnings("rawtypes")
@Override
protected void buildExcelDocument(Map<String, Object> map,
Workbook workbook, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws Exception {
try {
Assert.notEmpty(properties, "表格导出中属性为空");
Sheet sheet;
if (StringUtils.isNotEmpty(sheetName)) {
sheet = workbook.createSheet(sheetName);
} else {
sheet = workbook.createSheet();
}
int rowNumber = 0;
// 创建表头
if (titles != null && titles.length > 0) {
// HSSFRow header = sheet.createRow(rowNumber);
Row header = sheet.createRow(rowNumber);
header.setHeight((short) 400);
for (int i = 0; i < properties.length; i++) {
Cell cell = header.createCell(i);
CellStyle cellStyle = workbook.createCellStyle();
cellStyle
.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle
.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 11);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
if (i == 0) {
Drawing patriarch = sheet.createDrawingPatriarch();
Comment comment = patriarch
.createCellComment(new XSSFClientAnchor(0, 0,
0, 0, (short) 1, 1, (short) 4, 4));
comment.setString(new XSSFRichTextString("亿函科技公司版权所有"));
cell.setCellComment(comment);
}
if (titles.length > i && titles[i] != null) {
cell.setCellValue(titles[i]);
} else {
cell.setCellValue(properties[i]);
}
if (widths != null && widths.length > i
&& widths[i] != null) {
sheet.setColumnWidth(i, widths[i]);
} else {
sheet.autoSizeColumn(i);
}
}
rowNumber++;
}
// 写入数据
if (data != null) {
String property;
Convert convert;
Drawing drawing = sheet.createDrawingPatriarch();
for (Object item : data) {
Row row = sheet.createRow(rowNumber);
// 设置Excel表格高度(除标题以外)
if (this.bodyHeight != null) {
row.setHeightInPoints(this.bodyHeight);
}
for (int i = 0; i < properties.length; i++) {
Cell cell = row.createCell(i);
CellStyle cs = workbook.createCellStyle();
cs.setAlignment(CellStyle.ALIGN_CENTER); // 水平居中
cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER); // 垂直居中
cs.setWrapText(true); // 设置自动换行
cell.setCellStyle(cs);
property = properties[i];
convert = convertMap.get(property);
String value = null;
if (item instanceof Map) {
Object val = ((Map) item).get(property);
value = val == null ? null : val.toString();
} else {
value = BeanUtils.getProperty(item, property);
}
if (convert != null) {
value = convert.convert(value);
}
cell.setCellValue(value);
if (convert == null) {
cell.setCellValue(BeanUtils.getProperty(item,
property));
} else {
cell.setCellValue(convert.convert(BeanUtils
.getProperty(item, property)));
}
if (rowNumber == 0 || rowNumber == 1) {
if (widths != null && widths.length > i
&& widths[i] != null) {
sheet.setColumnWidth(i, widths[i]);
} else {
sheet.autoSizeColumn(i);
}
}
}
// 处理图片
if (pictures != null) {
for (int j = 0; j < pictures.length; j++) {
property = pictures[j];
String value = null;
if (item instanceof Map) {
Object val = ((Map) item).get(property);
value = val == null ? null : val.toString();
} else {
value = BeanUtils.getProperty(item, property);
}
if (StringUtils.isNotBlank(value)) {
// 清空图片地址
row.getCell(properties.length - 1 + j)
.setCellValue("");
// 将图片服务器上的图片转成byte数组
InputStream is = FileUtil
.remotePathToStream(value);
if (is != null) {
byte[] data = IOUtils.toByteArray(is);
// 写图片
XSSFClientAnchor anchor = new XSSFClientAnchor(
0,
0,
0,
0,
(short) (properties.length - 1 + j),
row.getRowNum(),
(short) (properties.length + j),
row.getRowNum() + 1);
drawing.createPicture(
anchor,
workbook.addPicture(
data,
XSSFWorkbook.PICTURE_TYPE_JPEG));
}
}
}
}
rowNumber++;
}
}
// 写入汇总信息
if (contents != null && contents.length > 0) {
rowNumber++;
for (String content : contents) {
Row row = sheet.createRow(rowNumber);
Cell cell = row.createCell(0);
CellStyle cellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setColor(HSSFColor.GREY_50_PERCENT.index);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
cell.setCellValue(content);
rowNumber++;
}
}
httpServletResponse.setContentType("application/force-download");
if (StringUtils.isNotEmpty(filename)) {
httpServletResponse.setHeader(
"Content-disposition",
"attachment; filename="
+ URLEncoder.encode(filename, "UTF-8"));
} else {
httpServletResponse.setHeader("Content-disposition",
"attachment");
}
} catch (Exception e) {
log.error(
"\r\n ************ Excle导出工具类方法【buildExcelDocument】报错:{}",
ExceptionUtils.getStackTrace(e));
}
}
/**
* 获取文件名称
*
* @return 文件名称
*/
public String getFileName() {
return filename;
}
/**
* 设置文件名称
*
* @param filename
* 文件名称
*/
public void setFileName(String filename) {
this.filename = filename;
}
/**
* 获取表名称
*
* @return 表名称
*/
public String getSheetName() {
return sheetName;
}
/**
* 设置表名称
*
* @param sheetName
* 表名称
*/
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
/**
* 获取属性
*
* @return 属性
*/
public String[] getProperties() {
return properties;
}
/**
* 设置属性
*
* @param properties
* 属性
*/
public void setProperties(String[] properties) {
this.properties = properties;
}
/**
* 获取标题
*
* @return 标题
*/
public String[] getTitles() {
return titles;
}
/**
* 设置标题
*
* @param titles
* 标题
*/
public void setTitles(String[] titles) {
this.titles = titles;
}
/**
* 获取图片属性集合
*/
public String[] getPictures() {
return pictures;
}
/**
* 设置图片属性集合
*/
public void setPictures(String[] pictures) {
this.pictures = pictures;
}
/**
* 获取列宽
*
* @return 列宽
*/
public Integer[] getWidths() {
return widths;
}
/**
* 设置列宽
*
* @param widths
* 列宽
*/
public void setWidths(Integer[] widths) {
this.widths = widths;
}
/**
* 获取表体高度
*/
public Float getBodyHeight() {
return bodyHeight;
}
/**
* 设置表体高度
*/
public void setBodyHeight(Float bodyHeight) {
this.bodyHeight = bodyHeight;
}
/**
* 获取数据
*
* @return 数据
*/
public Collection<?> getData() {
return data;
}
/**
* 设置数据
*
* @param data
* 数据
*/
public void setData(Collection<?> data) {
this.data = data;
}
/**
* 获取附加内容
*
* @return 附加内容
*/
public String[] getContents() {
return contents;
}
/**
* 设置附加内容
*
* @param contents
* 附加内容
*/
public void setContents(String[] contents) {
this.contents = contents;
}
}
//package cn.wisenergy.common.utils.exportView.view;
//
//import cn.wisenergy.common.utils.FileUtil;
//import cn.wisenergy.common.utils.exportView.convert.Convert;
//import org.apache.commons.beanutils.BeanUtils;
//import org.apache.commons.collections.MapUtils;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.apache.commons.lang3.exception.ExceptionUtils;
//import org.apache.poi.hssf.usermodel.HSSFCellStyle;
//import org.apache.poi.hssf.usermodel.HSSFFont;
//import org.apache.poi.hssf.util.HSSFColor;
//import org.apache.poi.ss.usermodel.*;
//import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
//import org.apache.poi.xssf.usermodel.XSSFRichTextString;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.util.Assert;
//import org.springframework.web.servlet.view.document.AbstractXlsxView;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.InputStream;
//import java.net.URLEncoder;
//import java.util.Collection;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * excel视图
// */
//public class ExcelView extends AbstractXlsxView {
//
// /**
// * 日志类
// */
// private Logger log = LoggerFactory.getLogger(this.getClass());
//
// /**
// * 文件名称
// */
// private String filename;
//
// /**
// * 表名称
// */
// private String sheetName;
//
// /**
// * 属性
// */
// private String[] properties;
//
// /**
// * 标题
// */
// private String[] titles;
//
// /**
// * 图片属性集合
// */
// private String[] pictures;
//
// /**
// * 列宽
// */
// private Integer[] widths;
//
// /**
// * 表体高度
// */
// private Float bodyHeight;
//
// /**
// * 数据
// */
// private Collection<?> data;
//
// /**
// * 附加内容
// */
// private String[] contents;
//
// /**
// * 数据转换map
// */
// private Map<String, Convert> convertMap = new HashMap<String, Convert>();
//
// /**
// * @param filename
// * 文件名称
// * @param sheetName
// * 表名称
// * @param properties
// * 属性
// * @param titles
// * 标题
// * @param widths
// * 列宽
// * @param data
// * 数据
// * @param contents
// * 附加内容
// * @param convertMap
// * 数据转化map
// */
// public ExcelView(String filename, String sheetName, String[] properties,
// String[] titles, Integer[] widths, Collection<?> data,
// String[] contents, Map<String, Convert> convertMap) {
// this.filename = filename;
// this.sheetName = sheetName;
// this.properties = properties;
// this.titles = titles;
// this.widths = widths;
// this.data = data;
// this.contents = contents;
// this.convertMap = MapUtils.isEmpty(convertMap) ? this.convertMap
// : convertMap;
// }
//
// /**
// * @param filename
// * 文件名称
// * @param sheetName
// * 表名称
// * @param properties
// * 属性
// * @param titles
// * 标题
// * @param pictures
// * 图片属性
// * @param widths
// * 列宽
// * @param bodyHeight
// * 表体高度
// * @param data
// * 数据
// * @param contents
// * 附加内容
// * @param convertMap
// * 数据转化map
// */
// public ExcelView(String filename, String sheetName, String[] properties,
// String[] titles, String[] pictures, Integer[] widths,
// Float bodyHeight, Collection<?> data, String[] contents,
// Map<String, Convert> convertMap) {
// this.filename = filename;
// this.sheetName = sheetName;
// this.properties = properties;
// this.titles = titles;
// this.pictures = pictures;
// this.widths = widths;
// this.bodyHeight = bodyHeight;
// this.data = data;
// this.contents = contents;
// this.convertMap = MapUtils.isEmpty(convertMap) ? this.convertMap
// : convertMap;
// }
//
// /**
// * @param properties
// * 属性
// * @param titles
// * 标题
// * @param data
// * 数据
// * @param contents
// * 附加内容
// */
// public ExcelView(String filename, String[] properties, String[] titles,
// Collection<?> data, String[] contents,
// Map<String, Convert> convertMap) {
// this.filename = filename;
// this.properties = properties;
// this.titles = titles;
// this.data = data;
// this.contents = contents;
// this.convertMap = MapUtils.isEmpty(convertMap) ? this.convertMap
// : convertMap;
// }
//
// /**
// * @param properties
// * 属性
// * @param titles
// * 标题
// * @param data
// * 数据
// */
// public ExcelView(String filename, String[] properties, String[] titles,
// Collection<?> data, Map<String, Convert> convertMap) {
// this.filename = filename;
// this.properties = properties;
// this.titles = titles;
// this.data = data;
// this.convertMap = MapUtils.isEmpty(convertMap) ? this.convertMap
// : convertMap;
// }
//
// /**
// * @param properties
// * 属性
// * @param data
// * 数据
// */
// public ExcelView(String[] properties, Collection<?> data) {
// this.properties = properties;
// this.data = data;
// }
//
// @SuppressWarnings("rawtypes")
// @Override
// protected void buildExcelDocument(Map<String, Object> map,
// Workbook workbook, HttpServletRequest httpServletRequest,
// HttpServletResponse httpServletResponse) throws Exception {
// try {
//
// Assert.notEmpty(properties, "表格导出中属性为空");
// Sheet sheet;
// if (StringUtils.isNotEmpty(sheetName)) {
// sheet = workbook.createSheet(sheetName);
// } else {
// sheet = workbook.createSheet();
// }
// int rowNumber = 0;
//
// // 创建表头
// if (titles != null && titles.length > 0) {
// // HSSFRow header = sheet.createRow(rowNumber);
// Row header = sheet.createRow(rowNumber);
// header.setHeight((short) 400);
// for (int i = 0; i < properties.length; i++) {
// Cell cell = header.createCell(i);
// CellStyle cellStyle = workbook.createCellStyle();
// cellStyle
// .setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
//// cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//// cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// //cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// Font font = workbook.createFont();
// font.setFontHeightInPoints((short) 11);
// //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// cellStyle.setFont(font);
// cell.setCellStyle(cellStyle);
//
// if (i == 0) {
// Drawing patriarch = sheet.createDrawingPatriarch();
// Comment comment = patriarch
// .createCellComment(new XSSFClientAnchor(0, 0,
// 0, 0, (short) 1, 1, (short) 4, 4));
// comment.setString(new XSSFRichTextString("亿函科技公司版权所有"));
// cell.setCellComment(comment);
// }
// if (titles.length > i && titles[i] != null) {
// cell.setCellValue(titles[i]);
// } else {
// cell.setCellValue(properties[i]);
// }
// if (widths != null && widths.length > i
// && widths[i] != null) {
// sheet.setColumnWidth(i, widths[i]);
// } else {
// sheet.autoSizeColumn(i);
// }
// }
// rowNumber++;
// }
//
// // 写入数据
// if (data != null) {
// String property;
// Convert convert;
// Drawing drawing = sheet.createDrawingPatriarch();
// for (Object item : data) {
// Row row = sheet.createRow(rowNumber);
// // 设置Excel表格高度(除标题以外)
// if (this.bodyHeight != null) {
// row.setHeightInPoints(this.bodyHeight);
// }
//
// for (int i = 0; i < properties.length; i++) {
// Cell cell = row.createCell(i);
// CellStyle cs = workbook.createCellStyle();
// //cs.setAlignment(CellStyle.ALIGN_CENTER); // 水平居中
// //cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER); // 垂直居中
// cs.setWrapText(true); // 设置自动换行
// cell.setCellStyle(cs);
//
// property = properties[i];
// convert = convertMap.get(property);
//
// String value = null;
// if (item instanceof Map) {
// Object val = ((Map) item).get(property);
// value = val == null ? null : val.toString();
// } else {
// value = BeanUtils.getProperty(item, property);
// }
// if (convert != null) {
// value = convert.convert(value);
// }
// cell.setCellValue(value);
// if (convert == null) {
// cell.setCellValue(BeanUtils.getProperty(item,
// property));
// } else {
// cell.setCellValue(convert.convert(BeanUtils
// .getProperty(item, property)));
// }
//
// if (rowNumber == 0 || rowNumber == 1) {
// if (widths != null && widths.length > i
// && widths[i] != null) {
// sheet.setColumnWidth(i, widths[i]);
// } else {
// sheet.autoSizeColumn(i);
// }
// }
// }
//
// // 处理图片
// if (pictures != null) {
// for (int j = 0; j < pictures.length; j++) {
// property = pictures[j];
// String value = null;
// if (item instanceof Map) {
// Object val = ((Map) item).get(property);
// value = val == null ? null : val.toString();
// } else {
// value = BeanUtils.getProperty(item, property);
// }
// if (StringUtils.isNotBlank(value)) {
//
// // 清空图片地址
// row.getCell(properties.length - 1 + j)
// .setCellValue("");
//
// // 将图片服务器上的图片转成byte数组
// InputStream is = FileUtil
// .remotePathToStream(value);
// if (is != null) {
// byte[] data = IOUtils.toByteArray(is);
// // 写图片
// XSSFClientAnchor anchor = new XSSFClientAnchor(
// 0,
// 0,
// 0,
// 0,
// (short) (properties.length - 1 + j),
// row.getRowNum(),
// (short) (properties.length + j),
// row.getRowNum() + 1);
// drawing.createPicture(
// anchor,
// workbook.addPicture(
// data,
// XSSFWorkbook.PICTURE_TYPE_JPEG));
// }
// }
// }
// }
//
// rowNumber++;
// }
// }
//
// // 写入汇总信息
// if (contents != null && contents.length > 0) {
// rowNumber++;
// for (String content : contents) {
// Row row = sheet.createRow(rowNumber);
// Cell cell = row.createCell(0);
// CellStyle cellStyle = workbook.createCellStyle();
// Font font = workbook.createFont();
// font.setColor(HSSFColor.GREY_50_PERCENT.index);
// cellStyle.setFont(font);
// cell.setCellStyle(cellStyle);
// cell.setCellValue(content);
// rowNumber++;
// }
// }
//
// httpServletResponse.setContentType("application/force-download");
// if (StringUtils.isNotEmpty(filename)) {
// httpServletResponse.setHeader(
// "Content-disposition",
// "attachment; filename="
// + URLEncoder.encode(filename, "UTF-8"));
// } else {
// httpServletResponse.setHeader("Content-disposition",
// "attachment");
// }
// } catch (Exception e) {
// log.error(
// "\r\n ************ Excle导出工具类方法【buildExcelDocument】报错:{}",
// ExceptionUtils.getStackTrace(e));
// }
// }
//
// /**
// * 获取文件名称
// *
// * @return 文件名称
// */
// public String getFileName() {
// return filename;
// }
//
// /**
// * 设置文件名称
// *
// * @param filename
// * 文件名称
// */
// public void setFileName(String filename) {
// this.filename = filename;
// }
//
// /**
// * 获取表名称
// *
// * @return 表名称
// */
// public String getSheetName() {
// return sheetName;
// }
//
// /**
// * 设置表名称
// *
// * @param sheetName
// * 表名称
// */
// public void setSheetName(String sheetName) {
// this.sheetName = sheetName;
// }
//
// /**
// * 获取属性
// *
// * @return 属性
// */
// public String[] getProperties() {
// return properties;
// }
//
// /**
// * 设置属性
// *
// * @param properties
// * 属性
// */
// public void setProperties(String[] properties) {
// this.properties = properties;
// }
//
// /**
// * 获取标题
// *
// * @return 标题
// */
// public String[] getTitles() {
// return titles;
// }
//
// /**
// * 设置标题
// *
// * @param titles
// * 标题
// */
// public void setTitles(String[] titles) {
// this.titles = titles;
// }
//
// /**
// * 获取图片属性集合
// */
// public String[] getPictures() {
// return pictures;
// }
//
// /**
// * 设置图片属性集合
// */
// public void setPictures(String[] pictures) {
// this.pictures = pictures;
// }
//
// /**
// * 获取列宽
// *
// * @return 列宽
// */
// public Integer[] getWidths() {
// return widths;
// }
//
// /**
// * 设置列宽
// *
// * @param widths
// * 列宽
// */
// public void setWidths(Integer[] widths) {
// this.widths = widths;
// }
//
// /**
// * 获取表体高度
// */
// public Float getBodyHeight() {
// return bodyHeight;
// }
//
// /**
// * 设置表体高度
// */
// public void setBodyHeight(Float bodyHeight) {
// this.bodyHeight = bodyHeight;
// }
//
// /**
// * 获取数据
// *
// * @return 数据
// */
// public Collection<?> getData() {
// return data;
// }
//
// /**
// * 设置数据
// *
// * @param data
// * 数据
// */
// public void setData(Collection<?> data) {
// this.data = data;
// }
//
// /**
// * 获取附加内容
// *
// * @return 附加内容
// */
// public String[] getContents() {
// return contents;
// }
//
// /**
// * 设置附加内容
// *
// * @param contents
// * 附加内容
// */
// public void setContents(String[] contents) {
// this.contents = contents;
// }
//
//}
......@@ -118,7 +118,7 @@
</foreach>
</insert>
<select id="getByProductNo" resultType="cn.wisenergy.model.app.AntiFake">
<select id="getByProductNo" resultMap="antiMap">
select
<include refid="cols_all"/>
from
......@@ -137,7 +137,7 @@
</where>
</select>
<select id="getList" resultType="cn.wisenergy.model.app.AntiFake">
<select id="getList" resultMap="antiMap">
select
<include refid="cols_all"/>
from
......@@ -149,8 +149,9 @@
</where>
</select>
<select id="getProductNos" resultType="cn.wisenergy.model.app.AntiFake">
select product_no
<select id="getProductNos" resultMap="antiMap">
select
<include refid="cols_all"/>
from
<include refid="table"/>
<where>
......@@ -162,7 +163,7 @@
</where>
</select>
<select id="getByShaValue" resultType="cn.wisenergy.model.app.AntiFake">
<select id="getByShaValue" resultMap="antiMap">
select
<include refid="cols_all"/>
from
......
package cn.wisenergy.model.app;
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
......@@ -50,6 +51,7 @@ public class AntiFake implements Serializable {
* 防伪码
*/
@ApiModelProperty(value = "防伪码", name = "shaValue")
@ExcelProperty(value = "防伪码")
private String shaValue;
/**
......
......@@ -63,4 +63,6 @@ public interface AntiFakeService {
* @return
*/
R<Boolean> report(String str, HttpServletResponse response);
void exportReceivable(String str, HttpServletResponse response);
}
......@@ -13,6 +13,7 @@ import cn.wisenergy.model.vo.ReportCodeVo;
import cn.wisenergy.service.Manager.AntiFakeManger;
import cn.wisenergy.service.app.AntiFakeService;
import cn.wisenergy.service.util.CodeUtils;
import cn.wisenergy.service.util.ExcelUtils;
import cn.wisenergy.service.util.QRCodeUtils;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
......@@ -203,15 +204,18 @@ public class AntiFakeServiceImpl extends ServiceImpl<AntiFakeMapper, AntiFake> i
return R.ok(false);
}
//获取防伪二维码生产
//获取防伪码
List<AntiFake> result = antiFakeMapper.getProductNos(array);
if (CollectionUtils.isEmpty(result)) {
return R.ok(0, true);
}
List<ReportCodeVo> resultBo = new ArrayList<>();
for (AntiFake anti : result) {
String url = REQUEST_URL + anti.getShaValue();
anti.setShaValue(url);
ReportCodeVo reportCodeVo = new ReportCodeVo();
reportCodeVo.setShaValue(url);
resultBo.add(reportCodeVo);
}
//生成Excel
......@@ -220,21 +224,13 @@ public class AntiFakeServiceImpl extends ServiceImpl<AntiFakeMapper, AntiFake> i
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 使用java8新特性的stream流去处理数据,把空的数据过滤掉
List<ReportCodeVo> resultBo = new ArrayList<>();
for (AntiFake antiFake : result) {
ReportCodeVo reportCodeVo = new ReportCodeVo();
reportCodeVo.setShaValue(antiFake.getShaValue());
resultBo.add(reportCodeVo);
}
//创建文件名称
long lon = System.currentTimeMillis();
response.setHeader("Content-disposition", "attachment;filename=" + lon + ".xlsx");
// sheet名称
EasyExcel.write(response.getOutputStream(), ReportCodeVo.class).sheet(Long.toString(lon)).doWrite(resultBo);
EasyExcel.write(response.getOutputStream(), AntiFake.class).sheet(Long.toString(lon)).doWrite(resultBo);
//修改二维码使用状态
boolean bool = antiFakeManger.updateAntiFake(array);
if (!bool) {
......@@ -246,6 +242,34 @@ public class AntiFakeServiceImpl extends ServiceImpl<AntiFakeMapper, AntiFake> i
}
}
@Override
public void exportReceivable(String str, HttpServletResponse response) {
if (StringUtils.isBlank(str)){
return;
}
//把字符转化为数字
List<Long> array = StringUtil.strToLongArray(str);
if (CollectionUtils.isEmpty(array)) {
return;
}
//获取防伪码
List<AntiFake> result = antiFakeMapper.getProductNos(array);
if (CollectionUtils.isEmpty(result)) {
return;
}
List<ReportCodeVo> resultBo = new ArrayList<>();
for (AntiFake anti : result) {
String url = REQUEST_URL + anti.getShaValue();
ReportCodeVo reportCodeVo = new ReportCodeVo();
reportCodeVo.setShaValue(url);
resultBo.add(reportCodeVo);
}
ExcelUtils.export(response, resultBo, "aadfgh", ReportCodeVo.class);
}
/**
* 分页处理方法
*
......
......@@ -6,14 +6,11 @@ import cn.wisenergy.service.app.LastMonthUserInfoService;
import cn.wisenergy.service.app.MonthUserLevelService;
import cn.wisenergy.service.app.UserLevelService;
import cn.wisenergy.service.app.UserLevelTaskService;
import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.model.IndexedUDFFinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
......
package cn.wisenergy.service.util;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import io.undertow.util.Headers;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* Excel工具类
*
* @author: ZHY
* @date: 2020-08-24 17:31
* @version:
**/
public class ExcelUtils {
private final static HorizontalCellStyleStrategy HORIZONTAL_CELL_STYLE_STRATEGY;
static {
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short) 12);
headWriteCellStyle.setWriteFont(headWriteFont);
// 内容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 内容字体
WriteFont contentWriteFont = new WriteFont();
// 字体大小
contentWriteFont.setFontHeightInPoints((short) 11);
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
HORIZONTAL_CELL_STYLE_STRATEGY = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
}
/**
* 导出
*
* @param response
* @param data 数据
* @param fileName 文件名
* @param t 导出对象
**/
public static <T> void export(HttpServletResponse response, List<T> data, String fileName, Class<T> t) {
try {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
response.setHeader(Headers.CONTENT_DISPOSITION_STRING, "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
EasyExcel.write(response.getOutputStream(), t)
.registerWriteHandler(HORIZONTAL_CELL_STYLE_STRATEGY)
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.sheet(fileName).doWrite(data);
} catch (Exception e) {
// 重置response
response.reset();
throw new RuntimeException("下载失败");
}
}
}
\ No newline at end of file
......@@ -36,13 +36,13 @@ public class AntiFakeController {
return antiFakeService.createCode(codeVo);
}
@ApiOperation(value = "扫描防伪二维码", notes = "扫描防伪二维码", httpMethod = "POST")
@ApiOperation(value = "扫描防伪二维码", notes = "扫描防伪二维码", httpMethod = "GET")
@ApiImplicitParams({
@ApiImplicitParam(name = "shaValue", value = "防伪码", dataType = "String",required = true),
@ApiImplicitParam(name = "securityCode", value = "安全码", dataType = "String",required = true)
})
@ApiImplicitParam(name = "shaValue", value = "防伪码", dataType = "String")
@PostMapping("/admin/scanCode")
@GetMapping("/admin/scanCode")
public R<String> scanCode(String shaValue,String securityCode) {
log.info("shop-mall[]AntiFakeController[]scanCode[]input.param.shaValue:" + shaValue,securityCode);
if (StringUtils.isBlank(shaValue)) {
......@@ -77,4 +77,16 @@ public class AntiFakeController {
return antiFakeService.report(ids, response);
}
// @ApiOperation(value = "导出二维码", notes = "获取防伪二维码分页列表", httpMethod = "GET")
// @ApiImplicitParam(name = "ids", value = " 二维码主键id :\"1,2,3,4,5,6,7,8,9,\"", dataType = "String")
// @GetMapping("admin/antiFakeService")
// public void antiFakeService(String ids, HttpServletResponse response) {
// log.info("shop-mall[]AntiFakeController[]antiFakeService[]input.param.ids:" + ids);
// if (StringUtils.isBlank(ids)) {
// return ;
// }
//
// antiFakeService.exportReceivable(ids, response);
// }
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment