新增MapExcelUnit mapExcel工具类已完成测试

This commit is contained in:
20932067@zju.edu.cn 2021-02-04 00:17:23 +08:00
parent 2a79f7002b
commit b72013fa34
8 changed files with 808 additions and 375 deletions

View File

@ -18,6 +18,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
@ -59,8 +60,7 @@ import com.hchyun.common.utils.reflect.ReflectUtils;
* *
* @author hchyun * @author hchyun
*/ */
public class ExcelUtil<T> public class ExcelUtil<T> {
{
private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class); private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
/** /**
@ -118,15 +118,12 @@ public class ExcelUtil<T>
*/ */
public Class<T> clazz; public Class<T> clazz;
public ExcelUtil(Class<T> clazz) public ExcelUtil(Class<T> clazz) {
{
this.clazz = clazz; this.clazz = clazz;
} }
public void init(List<T> list, String sheetName, Type type) public void init(List<T> list, String sheetName, Type type) {
{ if (list == null) {
if (list == null)
{
list = new ArrayList<T>(); list = new ArrayList<T>();
} }
this.list = list; this.list = list;
@ -142,8 +139,7 @@ public class ExcelUtil<T>
* @param is 输入流 * @param is 输入流
* @return 转换后集合 * @return 转换后集合
*/ */
public List<T> importExcel(InputStream is) throws Exception public List<T> importExcel(InputStream is) throws Exception {
{
return importExcel(StringUtils.EMPTY, is); return importExcel(StringUtils.EMPTY, is);
} }
@ -151,49 +147,39 @@ public class ExcelUtil<T>
* 对excel表单指定表格索引名转换成list * 对excel表单指定表格索引名转换成list
* *
* @param sheetName 表格索引名 * @param sheetName 表格索引名
* @param is 输入流 * @param is 输入流
* @return 转换后集合 * @return 转换后集合
*/ */
public List<T> importExcel(String sheetName, InputStream is) throws Exception public List<T> importExcel(String sheetName, InputStream is) throws Exception {
{
this.type = Type.IMPORT; this.type = Type.IMPORT;
this.wb = WorkbookFactory.create(is); this.wb = WorkbookFactory.create(is);
List<T> list = new ArrayList<T>(); List<T> list = new ArrayList<T>();
Sheet sheet = null; Sheet sheet = null;
if (StringUtils.isNotEmpty(sheetName)) if (StringUtils.isNotEmpty(sheetName)) {
{
// 如果指定sheet名,则取指定sheet中的内容. // 如果指定sheet名,则取指定sheet中的内容.
sheet = wb.getSheet(sheetName); sheet = wb.getSheet(sheetName);
} } else {
else
{
// 如果传入的sheet名不存在则默认指向第1个sheet. // 如果传入的sheet名不存在则默认指向第1个sheet.
sheet = wb.getSheetAt(0); sheet = wb.getSheetAt(0);
} }
if (sheet == null) if (sheet == null) {
{
throw new IOException("文件sheet不存在"); throw new IOException("文件sheet不存在");
} }
int rows = sheet.getPhysicalNumberOfRows(); int rows = sheet.getPhysicalNumberOfRows();
if (rows > 0) if (rows > 0) {
{
// 定义一个map用于存放excel列的序号和field. // 定义一个map用于存放excel列的序号和field.
Map<String, Integer> cellMap = new HashMap<String, Integer>(); Map<String, Integer> cellMap = new HashMap<String, Integer>();
// 获取表头 // 获取表头
Row heard = sheet.getRow(0); Row heard = sheet.getRow(0);
for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
{
Cell cell = heard.getCell(i); Cell cell = heard.getCell(i);
if (StringUtils.isNotNull(cell)) if (StringUtils.isNotNull(cell)) {
{
String value = this.getCellValue(heard, i).toString(); String value = this.getCellValue(heard, i).toString();
cellMap.put(value, i); cellMap.put(value, i);
} } else {
else
{
cellMap.put(null, i); cellMap.put(null, i);
} }
} }
@ -201,28 +187,23 @@ public class ExcelUtil<T>
Field[] allFields = clazz.getDeclaredFields(); Field[] allFields = clazz.getDeclaredFields();
// 定义一个map用于存放列的序号和field. // 定义一个map用于存放列的序号和field.
Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>(); Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
for (int col = 0; col < allFields.length; col++) for (int col = 0; col < allFields.length; col++) {
{
Field field = allFields[col]; Field field = allFields[col];
Excel attr = field.getAnnotation(Excel.class); Excel attr = field.getAnnotation(Excel.class);
if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
{
// 设置类的私有字段属性可访问. // 设置类的私有字段属性可访问.
field.setAccessible(true); field.setAccessible(true);
Integer column = cellMap.get(attr.name()); Integer column = cellMap.get(attr.name());
if (column != null) if (column != null) {
{
fieldsMap.put(column, field); fieldsMap.put(column, field);
} }
} }
} }
for (int i = 1; i < rows; i++) for (int i = 1; i < rows; i++) {
{
// 从第2行开始取数据,默认第一行是表头. // 从第2行开始取数据,默认第一行是表头.
Row row = sheet.getRow(i); Row row = sheet.getRow(i);
T entity = null; T entity = null;
for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet()) for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet()) {
{
Object val = this.getCellValue(row, entry.getKey()); Object val = this.getCellValue(row, entry.getKey());
// 如果不存在实例则新建. // 如果不存在实例则新建.
@ -231,63 +212,38 @@ public class ExcelUtil<T>
Field field = fieldsMap.get(entry.getKey()); Field field = fieldsMap.get(entry.getKey());
// 取得类型,并根据对象类型设置值. // 取得类型,并根据对象类型设置值.
Class<?> fieldType = field.getType(); Class<?> fieldType = field.getType();
if (String.class == fieldType) if (String.class == fieldType) {
{
String s = Convert.toStr(val); String s = Convert.toStr(val);
if (StringUtils.endsWith(s, ".0")) if (StringUtils.endsWith(s, ".0")) {
{
val = StringUtils.substringBefore(s, ".0"); val = StringUtils.substringBefore(s, ".0");
} } else {
else
{
val = Convert.toStr(val); val = Convert.toStr(val);
} }
} } else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val))) {
else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
{
val = Convert.toInt(val); val = Convert.toInt(val);
} } else if (Long.TYPE == fieldType || Long.class == fieldType) {
else if (Long.TYPE == fieldType || Long.class == fieldType)
{
val = Convert.toLong(val); val = Convert.toLong(val);
} } else if (Double.TYPE == fieldType || Double.class == fieldType) {
else if (Double.TYPE == fieldType || Double.class == fieldType)
{
val = Convert.toDouble(val); val = Convert.toDouble(val);
} } else if (Float.TYPE == fieldType || Float.class == fieldType) {
else if (Float.TYPE == fieldType || Float.class == fieldType)
{
val = Convert.toFloat(val); val = Convert.toFloat(val);
} } else if (BigDecimal.class == fieldType) {
else if (BigDecimal.class == fieldType)
{
val = Convert.toBigDecimal(val); val = Convert.toBigDecimal(val);
} } else if (Date.class == fieldType) {
else if (Date.class == fieldType) if (val instanceof String) {
{
if (val instanceof String)
{
val = DateUtils.parseDate(val); val = DateUtils.parseDate(val);
} } else if (val instanceof Double) {
else if (val instanceof Double)
{
val = DateUtil.getJavaDate((Double) val); val = DateUtil.getJavaDate((Double) val);
} }
} }
if (StringUtils.isNotNull(fieldType)) if (StringUtils.isNotNull(fieldType)) {
{
Excel attr = field.getAnnotation(Excel.class); Excel attr = field.getAnnotation(Excel.class);
String propertyName = field.getName(); String propertyName = field.getName();
if (StringUtils.isNotEmpty(attr.targetAttr())) if (StringUtils.isNotEmpty(attr.targetAttr())) {
{
propertyName = field.getName() + "." + attr.targetAttr(); propertyName = field.getName() + "." + attr.targetAttr();
} } else if (StringUtils.isNotEmpty(attr.readConverterExp())) {
else if (StringUtils.isNotEmpty(attr.readConverterExp()))
{
val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator()); val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
} } else if (StringUtils.isNotEmpty(attr.dictType())) {
else if (StringUtils.isNotEmpty(attr.dictType()))
{
val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator()); val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
} }
ReflectUtils.invokeSetter(entity, propertyName, val); ReflectUtils.invokeSetter(entity, propertyName, val);
@ -302,12 +258,11 @@ public class ExcelUtil<T>
/** /**
* 对list数据源将其里面的数据导入到excel表单 * 对list数据源将其里面的数据导入到excel表单
* *
* @param list 导出数据集合 * @param list 导出数据集合
* @param sheetName 工作表的名称 * @param sheetName 工作表的名称
* @return 结果 * @return 结果
*/ */
public AjaxResult exportExcel(List<T> list, String sheetName) public AjaxResult exportExcel(List<T> list, String sheetName) {
{
this.init(list, sheetName, Type.EXPORT); this.init(list, sheetName, Type.EXPORT);
return exportExcel(); return exportExcel();
} }
@ -318,8 +273,7 @@ public class ExcelUtil<T>
* @param sheetName 工作表的名称 * @param sheetName 工作表的名称
* @return 结果 * @return 结果
*/ */
public AjaxResult importTemplateExcel(String sheetName) public AjaxResult importTemplateExcel(String sheetName) {
{
this.init(null, sheetName, Type.IMPORT); this.init(null, sheetName, Type.IMPORT);
return exportExcel(); return exportExcel();
} }
@ -329,28 +283,23 @@ public class ExcelUtil<T>
* *
* @return 结果 * @return 结果
*/ */
public AjaxResult exportExcel() public AjaxResult exportExcel() {
{
OutputStream out = null; OutputStream out = null;
try try {
{
// 取出一共有多少个sheet. // 取出一共有多少个sheet.
double sheetNo = Math.ceil(list.size() / sheetSize); double sheetNo = Math.ceil(list.size() / sheetSize);
for (int index = 0; index <= sheetNo; index++) for (int index = 0; index <= sheetNo; index++) {
{
createSheet(sheetNo, index); createSheet(sheetNo, index);
// 产生一行 // 产生一行
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
int column = 0; int column = 0;
// 写入各个字段的列头名称 // 写入各个字段的列头名称
for (Object[] os : fields) for (Object[] os : fields) {
{
Excel excel = (Excel) os[1]; Excel excel = (Excel) os[1];
this.createCell(excel, row, column++); this.createCell(excel, row, column++);
} }
if (Type.EXPORT.equals(type)) if (Type.EXPORT.equals(type)) {
{
fillExcelData(index, row); fillExcelData(index, row);
addStatisticsRow(); addStatisticsRow();
} }
@ -359,33 +308,21 @@ public class ExcelUtil<T>
out = new FileOutputStream(getAbsoluteFile(filename)); out = new FileOutputStream(getAbsoluteFile(filename));
wb.write(out); wb.write(out);
return AjaxResult.success(filename); return AjaxResult.success(filename);
} } catch (Exception e) {
catch (Exception e)
{
log.error("导出Excel异常{}", e.getMessage()); log.error("导出Excel异常{}", e.getMessage());
throw new CustomException("导出Excel失败请联系网站管理员"); throw new CustomException("导出Excel失败请联系网站管理员");
} } finally {
finally if (wb != null) {
{ try {
if (wb != null)
{
try
{
wb.close(); wb.close();
} } catch (IOException e1) {
catch (IOException e1)
{
e1.printStackTrace(); e1.printStackTrace();
} }
} }
if (out != null) if (out != null) {
{ try {
try
{
out.close(); out.close();
} } catch (IOException e1) {
catch (IOException e1)
{
e1.printStackTrace(); e1.printStackTrace();
} }
} }
@ -396,20 +333,17 @@ public class ExcelUtil<T>
* 填充excel数据 * 填充excel数据
* *
* @param index 序号 * @param index 序号
* @param row 单元格行 * @param row 单元格行
*/ */
public void fillExcelData(int index, Row row) public void fillExcelData(int index, Row row) {
{
int startNo = index * sheetSize; int startNo = index * sheetSize;
int endNo = Math.min(startNo + sheetSize, list.size()); int endNo = Math.min(startNo + sheetSize, list.size());
for (int i = startNo; i < endNo; i++) for (int i = startNo; i < endNo; i++) {
{
row = sheet.createRow(i + 1 - startNo); row = sheet.createRow(i + 1 - startNo);
// 得到导出对象. // 得到导出对象.
T vo = (T) list.get(i); T vo = (T) list.get(i);
int column = 0; int column = 0;
for (Object[] os : fields) for (Object[] os : fields) {
{
Field field = (Field) os[0]; Field field = (Field) os[0];
Excel excel = (Excel) os[1]; Excel excel = (Excel) os[1];
// 设置实体类私有属性可访问 // 设置实体类私有属性可访问
@ -425,8 +359,7 @@ public class ExcelUtil<T>
* @param wb 工作薄对象 * @param wb 工作薄对象
* @return 样式列表 * @return 样式列表
*/ */
private Map<String, CellStyle> createStyles(Workbook wb) private Map<String, CellStyle> createStyles(Workbook wb) {
{
// 写入各条记录,每条记录对应excel表中的一行 // 写入各条记录,每条记录对应excel表中的一行
Map<String, CellStyle> styles = new HashMap<String, CellStyle>(); Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
CellStyle style = wb.createCellStyle(); CellStyle style = wb.createCellStyle();
@ -475,8 +408,7 @@ public class ExcelUtil<T>
/** /**
* 创建单元格 * 创建单元格
*/ */
public Cell createCell(Excel attr, Row row, int column) public Cell createCell(Excel attr, Row row, int column) {
{
// 创建列 // 创建列
Cell cell = row.createCell(column); Cell cell = row.createCell(column);
// 写入列信息 // 写入列信息
@ -490,18 +422,14 @@ public class ExcelUtil<T>
* 设置单元格信息 * 设置单元格信息
* *
* @param value 单元格值 * @param value 单元格值
* @param attr 注解相关 * @param attr 注解相关
* @param cell 单元格信息 * @param cell 单元格信息
*/ */
public void setCellVo(Object value, Excel attr, Cell cell) public void setCellVo(Object value, Excel attr, Cell cell) {
{ if (ColumnType.STRING == attr.cellType()) {
if (ColumnType.STRING == attr.cellType())
{
cell.setCellType(CellType.STRING); cell.setCellType(CellType.STRING);
cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix()); cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
} } else if (ColumnType.NUMERIC == attr.cellType()) {
else if (ColumnType.NUMERIC == attr.cellType())
{
cell.setCellType(CellType.NUMERIC); cell.setCellType(CellType.NUMERIC);
cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value)); cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
} }
@ -510,27 +438,22 @@ public class ExcelUtil<T>
/** /**
* 创建表格样式 * 创建表格样式
*/ */
public void setDataValidation(Excel attr, Row row, int column) public void setDataValidation(Excel attr, Row row, int column) {
{ String a = attr.name();
if (attr.name().indexOf("注:") >= 0) if (attr.name().indexOf("注:") >= 0) {
{
sheet.setColumnWidth(column, 6000); sheet.setColumnWidth(column, 6000);
} } else {
else
{
// 设置列宽 // 设置列宽
sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256)); sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
row.setHeight((short) (attr.height() * 20)); row.setHeight((short) (attr.height() * 20));
} }
// 如果设置了提示信息则鼠标放上去提示. // 如果设置了提示信息则鼠标放上去提示.
if (StringUtils.isNotEmpty(attr.prompt())) if (StringUtils.isNotEmpty(attr.prompt())) {
{
// 这里默认设了2-101列提示. // 这里默认设了2-101列提示.
setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column); setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
} }
// 如果设置了combo属性则本列只能选择不能输入 // 如果设置了combo属性则本列只能选择不能输入
if (attr.combo().length > 0) if (attr.combo().length > 0) {
{
// 这里默认设了2-101列只能选择不能输入. // 这里默认设了2-101列只能选择不能输入.
setXSSFValidation(sheet, attr.combo(), 1, 100, column, column); setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
} }
@ -539,16 +462,13 @@ public class ExcelUtil<T>
/** /**
* 添加单元格 * 添加单元格
*/ */
public Cell addCell(Excel attr, Row row, T vo, Field field, int column) public Cell addCell(Excel attr, Row row, T vo, Field field, int column) {
{
Cell cell = null; Cell cell = null;
try try {
{
// 设置行高 // 设置行高
row.setHeight((short) (attr.height() * 20)); row.setHeight((short) (attr.height() * 20));
// 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
if (attr.isExport()) if (attr.isExport()) {
{
// 创建cell // 创建cell
cell = row.createCell(column); cell = row.createCell(column);
cell.setCellStyle(styles.get("data")); cell.setCellStyle(styles.get("data"));
@ -559,32 +479,21 @@ public class ExcelUtil<T>
String readConverterExp = attr.readConverterExp(); String readConverterExp = attr.readConverterExp();
String separator = attr.separator(); String separator = attr.separator();
String dictType = attr.dictType(); String dictType = attr.dictType();
if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) {
{
cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value)); cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
} } else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) {
else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
{
cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator)); cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
} } else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value)) {
else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
{
cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator)); cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
} } else if (value instanceof BigDecimal && -1 != attr.scale()) {
else if (value instanceof BigDecimal && -1 != attr.scale())
{
cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString()); cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
} } else {
else
{
// 设置列类型 // 设置列类型
setCellVo(value, attr, cell); setCellVo(value, attr, cell);
} }
addStatisticsData(column, Convert.toStr(value), attr); addStatisticsData(column, Convert.toStr(value), attr);
} }
} } catch (Exception e) {
catch (Exception e)
{
log.error("导出Excel失败{}", e); log.error("导出Excel失败{}", e);
} }
return cell; return cell;
@ -593,17 +502,16 @@ public class ExcelUtil<T>
/** /**
* 设置 POI XSSFSheet 单元格提示 * 设置 POI XSSFSheet 单元格提示
* *
* @param sheet 表单 * @param sheet 表单
* @param promptTitle 提示标题 * @param promptTitle 提示标题
* @param promptContent 提示内容 * @param promptContent 提示内容
* @param firstRow 开始行 * @param firstRow 开始行
* @param endRow 结束行 * @param endRow 结束行
* @param firstCol 开始列 * @param firstCol 开始列
* @param endCol 结束列 * @param endCol 结束列
*/ */
public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
int firstCol, int endCol) int firstCol, int endCol) {
{
DataValidationHelper helper = sheet.getDataValidationHelper(); DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createCustomConstraint("DD1"); DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
@ -616,16 +524,15 @@ public class ExcelUtil<T>
/** /**
* 设置某些列的值只能输入预制的数据,显示下拉框. * 设置某些列的值只能输入预制的数据,显示下拉框.
* *
* @param sheet 要设置的sheet. * @param sheet 要设置的sheet.
* @param textlist 下拉框显示的内容 * @param textlist 下拉框显示的内容
* @param firstRow 开始行 * @param firstRow 开始行
* @param endRow 结束行 * @param endRow 结束行
* @param firstCol 开始列 * @param firstCol 开始列
* @param endCol 结束列 * @param endCol 结束列
* @return 设置好的sheet. * @return 设置好的sheet.
*/ */
public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
{
DataValidationHelper helper = sheet.getDataValidationHelper(); DataValidationHelper helper = sheet.getDataValidationHelper();
// 加载下拉列表内容 // 加载下拉列表内容
DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist); DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
@ -634,13 +541,10 @@ public class ExcelUtil<T>
// 数据有效性对象 // 数据有效性对象
DataValidation dataValidation = helper.createValidation(constraint, regions); DataValidation dataValidation = helper.createValidation(constraint, regions);
// 处理Excel兼容性问题 // 处理Excel兼容性问题
if (dataValidation instanceof XSSFDataValidation) if (dataValidation instanceof XSSFDataValidation) {
{
dataValidation.setSuppressDropDownArrow(true); dataValidation.setSuppressDropDownArrow(true);
dataValidation.setShowErrorBox(true); dataValidation.setShowErrorBox(true);
} } else {
else
{
dataValidation.setSuppressDropDownArrow(false); dataValidation.setSuppressDropDownArrow(false);
} }
@ -651,32 +555,24 @@ public class ExcelUtil<T>
* 解析导出值 0=,1=,2=未知 * 解析导出值 0=,1=,2=未知
* *
* @param propertyValue 参数值 * @param propertyValue 参数值
* @param converterExp 翻译注解 * @param converterExp 翻译注解
* @param separator 分隔符 * @param separator 分隔符
* @return 解析后值 * @return 解析后值
*/ */
public static String convertByExp(String propertyValue, String converterExp, String separator) public static String convertByExp(String propertyValue, String converterExp, String separator) {
{
StringBuilder propertyString = new StringBuilder(); StringBuilder propertyString = new StringBuilder();
String[] convertSource = converterExp.split(","); String[] convertSource = converterExp.split(",");
for (String item : convertSource) for (String item : convertSource) {
{
String[] itemArray = item.split("="); String[] itemArray = item.split("=");
if (StringUtils.containsAny(separator, propertyValue)) if (StringUtils.containsAny(separator, propertyValue)) {
{ for (String value : propertyValue.split(separator)) {
for (String value : propertyValue.split(separator)) if (itemArray[0].equals(value)) {
{
if (itemArray[0].equals(value))
{
propertyString.append(itemArray[1] + separator); propertyString.append(itemArray[1] + separator);
break; break;
} }
} }
} } else {
else if (itemArray[0].equals(propertyValue)) {
{
if (itemArray[0].equals(propertyValue))
{
return itemArray[1]; return itemArray[1];
} }
} }
@ -688,32 +584,24 @@ public class ExcelUtil<T>
* 反向解析值 =0,=1,未知=2 * 反向解析值 =0,=1,未知=2
* *
* @param propertyValue 参数值 * @param propertyValue 参数值
* @param converterExp 翻译注解 * @param converterExp 翻译注解
* @param separator 分隔符 * @param separator 分隔符
* @return 解析后值 * @return 解析后值
*/ */
public static String reverseByExp(String propertyValue, String converterExp, String separator) public static String reverseByExp(String propertyValue, String converterExp, String separator) {
{
StringBuilder propertyString = new StringBuilder(); StringBuilder propertyString = new StringBuilder();
String[] convertSource = converterExp.split(","); String[] convertSource = converterExp.split(",");
for (String item : convertSource) for (String item : convertSource) {
{
String[] itemArray = item.split("="); String[] itemArray = item.split("=");
if (StringUtils.containsAny(separator, propertyValue)) if (StringUtils.containsAny(separator, propertyValue)) {
{ for (String value : propertyValue.split(separator)) {
for (String value : propertyValue.split(separator)) if (itemArray[1].equals(value)) {
{
if (itemArray[1].equals(value))
{
propertyString.append(itemArray[0] + separator); propertyString.append(itemArray[0] + separator);
break; break;
} }
} }
} } else {
else if (itemArray[1].equals(propertyValue)) {
{
if (itemArray[1].equals(propertyValue))
{
return itemArray[0]; return itemArray[0];
} }
} }
@ -725,12 +613,11 @@ public class ExcelUtil<T>
* 解析字典值 * 解析字典值
* *
* @param dictValue 字典值 * @param dictValue 字典值
* @param dictType 字典类型 * @param dictType 字典类型
* @param separator 分隔符 * @param separator 分隔符
* @return 字典标签 * @return 字典标签
*/ */
public static String convertDictByExp(String dictValue, String dictType, String separator) public static String convertDictByExp(String dictValue, String dictType, String separator) {
{
return DictUtils.getDictLabel(dictType, dictValue, separator); return DictUtils.getDictLabel(dictType, dictValue, separator);
} }
@ -738,33 +625,26 @@ public class ExcelUtil<T>
* 反向解析值字典值 * 反向解析值字典值
* *
* @param dictLabel 字典标签 * @param dictLabel 字典标签
* @param dictType 字典类型 * @param dictType 字典类型
* @param separator 分隔符 * @param separator 分隔符
* @return 字典值 * @return 字典值
*/ */
public static String reverseDictByExp(String dictLabel, String dictType, String separator) public static String reverseDictByExp(String dictLabel, String dictType, String separator) {
{
return DictUtils.getDictValue(dictType, dictLabel, separator); return DictUtils.getDictValue(dictType, dictLabel, separator);
} }
/** /**
* 合计统计信息 * 合计统计信息
*/ */
private void addStatisticsData(Integer index, String text, Excel entity) private void addStatisticsData(Integer index, String text, Excel entity) {
{ if (entity != null && entity.isStatistics()) {
if (entity != null && entity.isStatistics())
{
Double temp = 0D; Double temp = 0D;
if (!statistics.containsKey(index)) if (!statistics.containsKey(index)) {
{
statistics.put(index, temp); statistics.put(index, temp);
} }
try try {
{
temp = Double.valueOf(text); temp = Double.valueOf(text);
} } catch (NumberFormatException e) {
catch (NumberFormatException e)
{
} }
statistics.put(index, statistics.get(index) + temp); statistics.put(index, statistics.get(index) + temp);
} }
@ -773,10 +653,8 @@ public class ExcelUtil<T>
/** /**
* 创建统计行 * 创建统计行
*/ */
public void addStatisticsRow() public void addStatisticsRow() {
{ if (statistics.size() > 0) {
if (statistics.size() > 0)
{
Cell cell = null; Cell cell = null;
Row row = sheet.createRow(sheet.getLastRowNum() + 1); Row row = sheet.createRow(sheet.getLastRowNum() + 1);
Set<Integer> keys = statistics.keySet(); Set<Integer> keys = statistics.keySet();
@ -784,8 +662,7 @@ public class ExcelUtil<T>
cell.setCellStyle(styles.get("total")); cell.setCellStyle(styles.get("total"));
cell.setCellValue("合计"); cell.setCellValue("合计");
for (Integer key : keys) for (Integer key : keys) {
{
cell = row.createCell(key); cell = row.createCell(key);
cell.setCellStyle(styles.get("total")); cell.setCellStyle(styles.get("total"));
cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key))); cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
@ -797,8 +674,7 @@ public class ExcelUtil<T>
/** /**
* 编码文件名 * 编码文件名
*/ */
public String encodingFilename(String filename) public String encodingFilename(String filename) {
{
filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx"; filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
return filename; return filename;
} }
@ -808,12 +684,10 @@ public class ExcelUtil<T>
* *
* @param filename 文件名称 * @param filename 文件名称
*/ */
public String getAbsoluteFile(String filename) public String getAbsoluteFile(String filename) {
{
String downloadPath = HchYunConfig.getDownloadPath() + filename; String downloadPath = HchYunConfig.getDownloadPath() + filename;
File desc = new File(downloadPath); File desc = new File(downloadPath);
if (!desc.getParentFile().exists()) if (!desc.getParentFile().exists()) {
{
desc.getParentFile().mkdirs(); desc.getParentFile().mkdirs();
} }
return downloadPath; return downloadPath;
@ -822,28 +696,22 @@ public class ExcelUtil<T>
/** /**
* 获取bean中的属性值 * 获取bean中的属性值
* *
* @param vo 实体对象 * @param vo 实体对象
* @param field 字段 * @param field 字段
* @param excel 注解 * @param excel 注解
* @return 最终的属性值 * @return 最终的属性值
* @throws Exception * @throws Exception
*/ */
private Object getTargetValue(T vo, Field field, Excel excel) throws Exception private Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
{
Object o = field.get(vo); Object o = field.get(vo);
if (StringUtils.isNotEmpty(excel.targetAttr())) if (StringUtils.isNotEmpty(excel.targetAttr())) {
{
String target = excel.targetAttr(); String target = excel.targetAttr();
if (target.indexOf(".") > -1) if (target.indexOf(".") > -1) {
{
String[] targets = target.split("[.]"); String[] targets = target.split("[.]");
for (String name : targets) for (String name : targets) {
{
o = getValue(o, name); o = getValue(o, name);
} }
} } else {
else
{
o = getValue(o, target); o = getValue(o, target);
} }
} }
@ -858,10 +726,8 @@ public class ExcelUtil<T>
* @return value * @return value
* @throws Exception * @throws Exception
*/ */
private Object getValue(Object o, String name) throws Exception private Object getValue(Object o, String name) throws Exception {
{ if (StringUtils.isNotEmpty(name)) {
if (StringUtils.isNotEmpty(name))
{
Class<?> clazz = o.getClass(); Class<?> clazz = o.getClass();
Field field = clazz.getDeclaredField(name); Field field = clazz.getDeclaredField(name);
field.setAccessible(true); field.setAccessible(true);
@ -873,27 +739,22 @@ public class ExcelUtil<T>
/** /**
* 得到所有定义字段 * 得到所有定义字段
*/ */
private void createExcelField() private void createExcelField() {
{
this.fields = new ArrayList<Object[]>(); this.fields = new ArrayList<Object[]>();
List<Field> tempFields = new ArrayList<>(); List<Field> tempFields = new ArrayList<>();
tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields())); tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
tempFields.addAll(Arrays.asList(clazz.getDeclaredFields())); tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
for (Field field : tempFields) for (Field field : tempFields) {
{
// 单注解 // 单注解
if (field.isAnnotationPresent(Excel.class)) if (field.isAnnotationPresent(Excel.class)) {
{
putToField(field, field.getAnnotation(Excel.class)); putToField(field, field.getAnnotation(Excel.class));
} }
// 多注解 // 多注解
if (field.isAnnotationPresent(Excels.class)) if (field.isAnnotationPresent(Excels.class)) {
{
Excels attrs = field.getAnnotation(Excels.class); Excels attrs = field.getAnnotation(Excels.class);
Excel[] excels = attrs.value(); Excel[] excels = attrs.value();
for (Excel excel : excels) for (Excel excel : excels) {
{
putToField(field, excel); putToField(field, excel);
} }
} }
@ -904,19 +765,16 @@ public class ExcelUtil<T>
/** /**
* 放到字段集合中 * 放到字段集合中
*/ */
private void putToField(Field field, Excel attr) private void putToField(Field field, Excel attr) {
{ if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) this.fields.add(new Object[]{field, attr});
{
this.fields.add(new Object[] { field, attr });
} }
} }
/** /**
* 创建一个工作簿 * 创建一个工作簿
*/ */
public void createWorkbook() public void createWorkbook() {
{
this.wb = new SXSSFWorkbook(500); this.wb = new SXSSFWorkbook(500);
} }
@ -924,19 +782,15 @@ public class ExcelUtil<T>
* 创建工作表 * 创建工作表
* *
* @param sheetNo sheet数量 * @param sheetNo sheet数量
* @param index 序号 * @param index 序号
*/ */
public void createSheet(double sheetNo, int index) public void createSheet(double sheetNo, int index) {
{
this.sheet = wb.createSheet(); this.sheet = wb.createSheet();
this.styles = createStyles(wb); this.styles = createStyles(wb);
// 设置工作表的名称. // 设置工作表的名称.
if (sheetNo == 0) if (sheetNo == 0) {
{
wb.setSheetName(index, sheetName); wb.setSheetName(index, sheetName);
} } else {
else
{
wb.setSheetName(index, sheetName + index); wb.setSheetName(index, sheetName + index);
} }
} }
@ -944,58 +798,39 @@ public class ExcelUtil<T>
/** /**
* 获取单元格值 * 获取单元格值
* *
* @param row 获取的行 * @param row 获取的行
* @param column 获取单元格列号 * @param column 获取单元格列号
* @return 单元格值 * @return 单元格值
*/ */
public Object getCellValue(Row row, int column) public Object getCellValue(Row row, int column) {
{ if (row == null) {
if (row == null)
{
return row; return row;
} }
Object val = ""; Object val = "";
try try {
{
Cell cell = row.getCell(column); Cell cell = row.getCell(column);
if (StringUtils.isNotNull(cell)) if (StringUtils.isNotNull(cell)) {
{ if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA) {
if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA)
{
val = cell.getNumericCellValue(); val = cell.getNumericCellValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) if (HSSFDateUtil.isCellDateFormatted(cell)) {
{
val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换 val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
} } else {
else if ((Double) val % 1 > 0) {
{
if ((Double) val % 1 > 0)
{
val = new BigDecimal(val.toString()); val = new BigDecimal(val.toString());
} } else {
else
{
val = new DecimalFormat("0").format(val); val = new DecimalFormat("0").format(val);
} }
} }
} } else if (cell.getCellTypeEnum() == CellType.STRING) {
else if (cell.getCellTypeEnum() == CellType.STRING)
{
val = cell.getStringCellValue(); val = cell.getStringCellValue();
} } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
else if (cell.getCellTypeEnum() == CellType.BOOLEAN)
{
val = cell.getBooleanCellValue(); val = cell.getBooleanCellValue();
} } else if (cell.getCellTypeEnum() == CellType.ERROR) {
else if (cell.getCellTypeEnum() == CellType.ERROR)
{
val = cell.getErrorCellValue(); val = cell.getErrorCellValue();
} }
} }
} } catch (Exception e) {
catch (Exception e)
{
return val; return val;
} }
return val; return val;

View File

@ -11,6 +11,7 @@ import com.hchyun.generator.entity.UniCon;
import com.hchyun.generator.entity.UniQuery; import com.hchyun.generator.entity.UniQuery;
import com.hchyun.generator.service.QueryService; import com.hchyun.generator.service.QueryService;
import com.hchyun.generator.service.UniQueryService; import com.hchyun.generator.service.UniQueryService;
import com.hchyun.generator.util.MapExcelUtil;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -66,8 +67,8 @@ public class QueryController extends BaseController {
@PreAuthorize("@ss.hasAnyPermi('query:real:data')") @PreAuthorize("@ss.hasAnyPermi('query:real:data')")
@PutMapping("/real") @GetMapping("/real")
public Serializable RealData(@Validated @RequestBody UniQuery uniQuery) { public Serializable RealData(@Validated UniQuery uniQuery) {
try { try {
ServerResult<List<Map<String, Object>>> serverResult = queryService.RealData(uniQuery); ServerResult<List<Map<String, Object>>> serverResult = queryService.RealData(uniQuery);
if (serverResult.isStart()) { if (serverResult.isStart()) {
@ -137,6 +138,7 @@ public class QueryController extends BaseController {
startPage(uniQuery); startPage(uniQuery);
ServerResult<List<Map<String, Object>>> serverResult = queryService.previewQuery(uniQuery); ServerResult<List<Map<String, Object>>> serverResult = queryService.previewQuery(uniQuery);
if (serverResult.isStart()) { if (serverResult.isStart()) {
MapExcelUtil util = new MapExcelUtil();
return getDataTable(serverResult.getData()); return getDataTable(serverResult.getData());
} else { } else {
return AjaxResult.error(serverResult.getMsg()); return AjaxResult.error(serverResult.getMsg());

View File

@ -111,11 +111,10 @@ public class QueryServiceImpl implements QueryService {
return new ServerResult<List<Map<String, Object>>>(false, ReturnConstants.STATE_ERROR); return new ServerResult<List<Map<String, Object>>>(false, ReturnConstants.STATE_ERROR);
} else { } else {
if (uniCons.size() > 0) { if (uniCons.size() > 0) {
sql += " where "; sql += " where 1 = 1 ";
for (UniCon uniCon : uniCons) { for (UniCon uniCon : uniCons) {
sql += conversionReal(uniCon); sql += conversionReal(uniCon);
} }
sql += " 1 = 1";
} }
PageHelper.startPage(pageNum, pageSize, ""); PageHelper.startPage(pageNum, pageSize, "");
List<Map<String, Object>> dataMap = queryDao.UniQuery(sql); List<Map<String, Object>> dataMap = queryDao.UniQuery(sql);
@ -166,11 +165,10 @@ public class QueryServiceImpl implements QueryService {
return new ServerResult<List<Map<String, Object>>>(false, "sql语句含有insert,delete,update,drop,database,view,alter等特殊字符!"); return new ServerResult<List<Map<String, Object>>>(false, "sql语句含有insert,delete,update,drop,database,view,alter等特殊字符!");
} }
if (uniConList.size() > 0) { if (uniConList.size() > 0) {
sql = sql + " where "; sql = sql + " where 1 = 1";
for (UniCon uniCon : uniConList) { for (UniCon uniCon : uniConList) {
sql += conversionPreview(uniCon); sql += conversionPreview(uniCon);
} }
sql += " 1 = 1";
} }
List<Map<String, Object>> dataMap = queryDao.UniQuery(sql); List<Map<String, Object>> dataMap = queryDao.UniQuery(sql);
return new ServerResult<List<Map<String, Object>>>(true, dataMap); return new ServerResult<List<Map<String, Object>>>(true, dataMap);
@ -196,40 +194,39 @@ public class QueryServiceImpl implements QueryService {
if (uniCon.getUcReal() == null) { if (uniCon.getUcReal() == null) {
return ""; return "";
} else { } else {
String sql = ""; String sql = " and ";
if (uniCon.getUcCon().equals("EQ")) { if (uniCon.getUcCon().equals("EQ")) {
sql += uniCon.getUcKey() + " = '" + uniCon.getUcReal() + "' and "; sql += uniCon.getUcKey() + " = '" + uniCon.getUcReal() + "'";
} else if (uniCon.getUcCon().equals("NE")) { } else if (uniCon.getUcCon().equals("NE")) {
sql += uniCon.getUcKey() + " != '" + uniCon.getUcReal() + "' and "; sql += uniCon.getUcKey() + " != '" + uniCon.getUcReal() + "'";
} else if (uniCon.getUcCon().equals("GT")) { } else if (uniCon.getUcCon().equals("GT")) {
sql += uniCon.getUcKey() + " > '" + uniCon.getUcReal() + "' and "; sql += uniCon.getUcKey() + " > '" + uniCon.getUcReal() + "'";
} else if (uniCon.getUcCon().equals("GTE")) { } else if (uniCon.getUcCon().equals("GTE")) {
sql += uniCon.getUcKey() + " >= '" + uniCon.getUcReal() + "' and "; sql += uniCon.getUcKey() + " >= '" + uniCon.getUcReal() + "'";
} else if (uniCon.getUcCon().equals("LT")) { } else if (uniCon.getUcCon().equals("LT")) {
sql += uniCon.getUcKey() + " < '" + uniCon.getUcReal() + "' and "; sql += uniCon.getUcKey() + " < '" + uniCon.getUcReal() + "'";
} else if (uniCon.getUcCon().equals("LTE")) { } else if (uniCon.getUcCon().equals("LTE")) {
sql += uniCon.getUcKey() + " <= '" + uniCon.getUcReal() + "' and "; sql += uniCon.getUcKey() + " <= '" + uniCon.getUcReal() + "'";
} else if (uniCon.getUcCon().equals("LIKE")) { } else if (uniCon.getUcCon().equals("LIKE")) {
sql += uniCon.getUcKey() + " like '%" + uniCon.getUcReal() + "%' and "; sql += uniCon.getUcKey() + " like '%" + uniCon.getUcReal() + "%'";
} else if (uniCon.getUcCon().equals("BETWEEN")) { } else if (uniCon.getUcCon().equals("BETWEEN")) {
if (uniCon.getUcType().equals("input")) { if (uniCon.getUcType().equals("input")) {
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(uniCon.getUcReal()); JSONObject jsonObject = (JSONObject) JSONObject.toJSON(uniCon.getUcReal());
Object begin = jsonObject.get("begin"); Object begin = jsonObject.get("begin");
Object end = jsonObject.get("end"); Object end = jsonObject.get("end");
sql += uniCon.getUcKey() + " between '" + begin + "' AND '" + end + "' and "; sql += uniCon.getUcKey() + " between '" + begin + "' AND '" + end + "'";
} else if (uniCon.getUcType().equals("datetime")) { } else if (uniCon.getUcType().equals("datetime")) {
List<String> list = (ArrayList<String>) uniCon.getUcReal(); List<String> list = (ArrayList<String>) uniCon.getUcReal();
if (list.size() == 2) { if (list.size() == 2) {
String startTime = list.get(0); String startTime = list.get(0);
String endTime = list.get(1); String endTime = list.get(1);
sql += uniCon.getUcKey() + " between '" + startTime + "' AND '" + endTime + "' and "; sql += uniCon.getUcKey() + " between '" + startTime + "' AND '" + endTime + "'";
} else { } else {
sql = ""; sql = "";
} }
} }
} }
return sql; return sql;
} }
} }
@ -237,31 +234,31 @@ public class QueryServiceImpl implements QueryService {
if (uniCon.getType().equals("datetime")) { if (uniCon.getType().equals("datetime")) {
uniCon.setUcMock(DateUtils.getDate(uniCon.getUcMock())); uniCon.setUcMock(DateUtils.getDate(uniCon.getUcMock()));
} }
String sql = ""; String sql = " and ";
if (uniCon.getUcCon().equals("EQ")) { if (uniCon.getUcCon().equals("EQ")) {
sql += uniCon.getUcKey() + " = '" + uniCon.getUcMock() + "' and "; sql += uniCon.getUcKey() + " = '" + uniCon.getUcMock() + "'";
} else if (uniCon.getUcCon().equals("NE")) { } else if (uniCon.getUcCon().equals("NE")) {
sql += uniCon.getUcKey() + " != '" + uniCon.getUcMock() + "' and "; sql += uniCon.getUcKey() + " != '" + uniCon.getUcMock() + "'";
} else if (uniCon.getUcCon().equals("GT")) { } else if (uniCon.getUcCon().equals("GT")) {
sql += uniCon.getUcKey() + " > '" + uniCon.getUcMock() + "' and "; sql += uniCon.getUcKey() + " > '" + uniCon.getUcMock() + "'";
} else if (uniCon.getUcCon().equals("GTE")) { } else if (uniCon.getUcCon().equals("GTE")) {
sql += uniCon.getUcKey() + " >= '" + uniCon.getUcMock() + "' and "; sql += uniCon.getUcKey() + " >= '" + uniCon.getUcMock() + "'";
} else if (uniCon.getUcCon().equals("LT")) { } else if (uniCon.getUcCon().equals("LT")) {
sql += uniCon.getUcKey() + " < '" + uniCon.getUcMock() + "' and "; sql += uniCon.getUcKey() + " < '" + uniCon.getUcMock() + "'";
} else if (uniCon.getUcCon().equals("LTE")) { } else if (uniCon.getUcCon().equals("LTE")) {
sql += uniCon.getUcKey() + " <= '" + uniCon.getUcMock() + "' and "; sql += uniCon.getUcKey() + " <= '" + uniCon.getUcMock() + "'";
} else if (uniCon.getUcCon().equals("LIKE")) { } else if (uniCon.getUcCon().equals("LIKE")) {
sql += uniCon.getUcKey() + " like '%" + uniCon.getUcMock() + "%' and "; sql += uniCon.getUcKey() + " like '%" + uniCon.getUcMock() + "%'";
} else if (uniCon.getUcCon().equals("BETWEEN")) { } else if (uniCon.getUcCon().equals("BETWEEN")) {
JSONObject jsonObject = JSONObject.parseObject(uniCon.getUcMock()); JSONObject jsonObject = JSONObject.parseObject(uniCon.getUcMock());
if (uniCon.getUcType().equals("input")) { if (uniCon.getUcType().equals("input")) {
Object begin = jsonObject.get("begin"); Object begin = jsonObject.get("begin");
Object end = jsonObject.get("end"); Object end = jsonObject.get("end");
sql += uniCon.getUcKey() + " between '" + begin + "' AND '" + end + "' and "; sql += uniCon.getUcKey() + " between '" + begin + "' AND '" + end + "'";
} else if (uniCon.getUcType().equals("datetime")) { } else if (uniCon.getUcType().equals("datetime")) {
Object startTime = jsonObject.get("startTime"); Object startTime = jsonObject.get("startTime");
Object endTime = jsonObject.get("endTime"); Object endTime = jsonObject.get("endTime");
sql += uniCon.getUcKey() + " between '" + startTime + "' AND '" + endTime + "' and "; sql += uniCon.getUcKey() + " between '" + startTime + "' AND '" + endTime + "'";
} }
} }
return sql; return sql;

View File

@ -0,0 +1,296 @@
package com.hchyun.generator.util;
import com.hchyun.common.config.HchYunConfig;
import com.hchyun.common.core.entity.AjaxResult;
import com.hchyun.common.exception.CustomException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
/**
* @Author 18209
* @Date 2021/2/3 21:09
* @Version 1.0
*/
public class MapExcelUtil<T> {
private Logger logger = LoggerFactory.getLogger(MapExcelUtil.class);
/**
* Excel sheet最大行数默认65536
*/
public static final int sheetSize = 65536;
/**
* 工作表名称
*/
private String sheetName;
/**
* 工作薄对象
*/
private Workbook wb;
/**
* 工作表对象
*/
private Sheet sheet;
/**
* 样式列表
*/
private Map<String, CellStyle> styles;
/**
* 导入导出数据列表
*/
private List<Map<String, Object>> list;
/**
* 注解列表
*/
private List<String> herders;
/**
* 对list数据源将其里面的数据导入到excel表单
*
* @param list 导出数据集合
* @param sheetName 工作表的名称
* @return 结果
*/
public AjaxResult exportExcel(List<Map<String, Object>> list, String sheetName) {
this.init(list, sheetName);
return exportExcel();
}
public void init(List<Map<String, Object>> list, String sheetName) {
if (list == null) {
list = new ArrayList<Map<String, Object>>();
}
this.list = list;
this.sheetName = sheetName;
createExcelField();
createWorkbook();
}
/**
* 创建一个工作簿
*/
public void createWorkbook() {
this.wb = new SXSSFWorkbook(500);
}
/**
* 得到所有定义字段
*/
private void createExcelField() {
this.herders = new ArrayList<String>();
Map<String, Object> modeMap = this.list.get(0);
for (String key : modeMap.keySet()) {
this.herders.add(key);
}
}
/**
* 创建表格样式
*
* @param wb 工作薄对象
* @return 样式列表
*/
private Map<String, CellStyle> createStyles(Workbook wb) {
// 写入各条记录,每条记录对应excel表中的一行
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
Font dataFont = wb.createFont();
dataFont.setFontName("Arial");
dataFont.setFontHeightInPoints((short) 10);
style.setFont(dataFont);
styles.put("data", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font headerFont = wb.createFont();
headerFont.setFontName("Arial");
headerFont.setFontHeightInPoints((short) 10);
headerFont.setBold(true);
headerFont.setColor(IndexedColors.WHITE.getIndex());
style.setFont(headerFont);
styles.put("header", style);
style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
Font totalFont = wb.createFont();
totalFont.setFontName("Arial");
totalFont.setFontHeightInPoints((short) 10);
style.setFont(totalFont);
styles.put("total", style);
return styles;
}
/**
* 创建工作表
*
* @param sheetNo sheet数量
* @param index 序号
*/
public void createSheet(double sheetNo, int index) {
this.sheet = wb.createSheet();
this.styles = createStyles(wb);
// 设置工作表的名称.
if (sheetNo == 0) {
wb.setSheetName(index, sheetName);
} else {
wb.setSheetName(index, sheetName + index);
}
}
/**
* 填充excel数据
*
* @param index 序号
* @param row 单元格行
*/
public void fillExcelData(int index, Row row) {
int startNo = index * sheetSize;
int endNo = Math.min(startNo + sheetSize, list.size());
for (int i = startNo; i < endNo; i++) {
row = sheet.createRow(i + 1 - startNo);
int column = 0;
//获取内容
for (int k=0;i<this.herders.size();i++) {
// 填充单元格的值
this.addCell(row, this.herders.get(i), column,k++);
}
column++;
}
}
/**
* 添加单元格
*/
public Cell addCell(Row row, String key, int column,Integer k) {
Cell cell = null;
try {
// 设置行高
row.setHeight((short) 280);
// 创建cell
cell = row.createCell(k);
cell.setCellStyle(styles.get("data"));
Object value = this.list.get(column).get(key);
cell.setCellValue(value.toString());
} catch (Exception e) {
logger.error("导出Excel失败{}", e);
}
return cell;
}
/**
* 创建单元格
*/
public Cell createCell(Row row, String herder, int column) {
// 创建列
Cell cell = row.createCell(column);
// 写入列信息
cell.setCellValue(herder);
cell.setCellStyle(styles.get("header"));
return cell;
}
/**
* 编码文件名
*/
public String encodingFilename(String filename) {
filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
return filename;
}
/**
* 获取下载路径
*
* @param filename 文件名称
*/
public String getAbsoluteFile(String filename) {
String downloadPath = HchYunConfig.getDownloadPath() + filename;
File desc = new File(downloadPath);
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
return downloadPath;
}
/**
* 对list数据源将其里面的数据导入到excel表单
*
* @return 结果
*/
public AjaxResult exportExcel() {
OutputStream out = null;
try {
// 取出一共有多少个sheet.
double sheetNo = Math.ceil(list.size() / sheetSize);
for (int index = 0; index <= sheetNo; index++) {
createSheet(sheetNo, index);
// 产生一行
Row row = sheet.createRow(0);
int column = 0;
// 写入各个字段的列头名称
for (String herder : herders) {
//设置列名称
this.createCell(row, herder, column++);
}
fillExcelData(index, row);
}
String filename = encodingFilename(sheetName);
out = new FileOutputStream(getAbsoluteFile(filename));
wb.write(out);
return AjaxResult.success(filename);
} catch (Exception e) {
logger.error("导出Excel异常{}", e.getMessage());
throw new CustomException("导出Excel失败请联系网站管理员");
} finally {
if (wb != null) {
try {
wb.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}

View File

@ -0,0 +1,295 @@
package com.hchyun.test;
import com.hchyun.common.config.HchYunConfig;
import com.hchyun.common.core.entity.AjaxResult;
import com.hchyun.common.exception.CustomException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
/**
* @Author 18209
* @Date 2021/2/3 21:09
* @Version 1.0
*/
public class MapExcelUtil<T> {
private Logger logger = LoggerFactory.getLogger(MapExcelUtil.class);
/**
* Excel sheet最大行数默认65536
*/
public static final int sheetSize = 65536;
/**
* 工作表名称
*/
private String sheetName;
/**
* 工作薄对象
*/
private Workbook wb;
/**
* 工作表对象
*/
private Sheet sheet;
/**
* 样式列表
*/
private Map<String, CellStyle> styles;
/**
* 导入导出数据列表
*/
private List<Map<String, Object>> list;
/**
* 注解列表
*/
private List<String> herders;
/**
* 对list数据源将其里面的数据导入到excel表单
*
* @param list 导出数据集合
* @param sheetName 工作表的名称
* @return 结果
*/
public AjaxResult exportExcel(List<Map<String, Object>> list, String sheetName) {
this.init(list, sheetName);
return exportExcel();
}
public void init(List<Map<String, Object>> list, String sheetName) {
if (list == null) {
list = new ArrayList<Map<String, Object>>();
}
this.list = list;
this.sheetName = sheetName;
createExcelField();
createWorkbook();
}
/**
* 创建一个工作簿
*/
public void createWorkbook() {
this.wb = new SXSSFWorkbook(500);
}
/**
* 得到所有定义字段
*/
private void createExcelField() {
this.herders = new ArrayList<String>();
Map<String, Object> modeMap = this.list.get(0);
for (String key : modeMap.keySet()) {
this.herders.add(key);
}
}
/**
* 创建表格样式
*
* @param wb 工作薄对象
* @return 样式列表
*/
private Map<String, CellStyle> createStyles(Workbook wb) {
// 写入各条记录,每条记录对应excel表中的一行
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
Font dataFont = wb.createFont();
dataFont.setFontName("Arial");
dataFont.setFontHeightInPoints((short) 10);
style.setFont(dataFont);
styles.put("data", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font headerFont = wb.createFont();
headerFont.setFontName("Arial");
headerFont.setFontHeightInPoints((short) 10);
headerFont.setBold(true);
headerFont.setColor(IndexedColors.WHITE.getIndex());
style.setFont(headerFont);
styles.put("header", style);
style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
Font totalFont = wb.createFont();
totalFont.setFontName("Arial");
totalFont.setFontHeightInPoints((short) 10);
style.setFont(totalFont);
styles.put("total", style);
return styles;
}
/**
* 创建工作表
*
* @param sheetNo sheet数量
* @param index 序号
*/
public void createSheet(double sheetNo, int index) {
this.sheet = wb.createSheet();
this.styles = createStyles(wb);
// 设置工作表的名称.
if (sheetNo == 0) {
wb.setSheetName(index, sheetName);
} else {
wb.setSheetName(index, sheetName + index);
}
}
/**
* 填充excel数据
*
* @param index 序号
* @param row 单元格行
*/
public void fillExcelData(int index, Row row) {
int startNo = index * sheetSize;
int endNo = Math.min(startNo + sheetSize, list.size());
for (int i = startNo; i < endNo; i++) {
row = sheet.createRow(i + 1 - startNo);
//获取内容
int k = 0;
for (String key : herders) {
// 填充单元格的值
this.addCell(row, key, i,k++);
}
}
}
/**
* 添加单元格
*/
public Cell addCell(Row row, String key, int column,Integer k) {
Cell cell = null;
try {
// 设置行高
row.setHeight((short) 280);
// 创建cell
cell = row.createCell(k);
cell.setCellStyle(styles.get("data"));
Object value = this.list.get(column).get(key);
cell.setCellValue(value.toString());
} catch (Exception e) {
logger.error("导出Excel失败{}", e);
}
return cell;
}
/**
* 创建单元格
*/
public Cell createCell(Row row, String herder, int column) {
// 创建列
Cell cell = row.createCell(column);
// 写入列信息
cell.setCellValue(herder);
cell.setCellStyle(styles.get("header"));
return cell;
}
/**
* 编码文件名
*/
public String encodingFilename(String filename) {
filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
return filename;
}
/**
* 获取下载路径
*
* @param filename 文件名称
*/
public String getAbsoluteFile(String filename) {
String downloadPath = HchYunConfig.getDownloadPath() + filename;
File desc = new File(downloadPath);
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
return downloadPath;
}
/**
* 对list数据源将其里面的数据导入到excel表单
*
* @return 结果
*/
public AjaxResult exportExcel() {
OutputStream out = null;
try {
// 取出一共有多少个sheet.
double sheetNo = Math.ceil(list.size() / sheetSize);
for (int index = 0; index <= sheetNo; index++) {
createSheet(sheetNo, index);
// 产生一行
Row row = sheet.createRow(0);
int column = 0;
// 写入各个字段的列头名称
for (String herder : herders) {
//设置列名称
this.createCell(row, herder, column++);
}
fillExcelData(index, row);
}
String filename = encodingFilename(sheetName);
out = new FileOutputStream(getAbsoluteFile(filename));
wb.write(out);
return AjaxResult.success(filename);
} catch (Exception e) {
logger.error("导出Excel异常{}", e.getMessage());
throw new CustomException("导出Excel失败请联系网站管理员");
} finally {
if (wb != null) {
try {
wb.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}

View File

@ -5,6 +5,7 @@ import java.util.List;
import com.hchyun.common.constant.ReturnConstants; import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.core.controller.HcyBaseController; import com.hchyun.common.core.controller.HcyBaseController;
import com.hchyun.common.exception.CustomException;
import com.hchyun.common.utils.ServerResult; import com.hchyun.common.utils.ServerResult;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
@ -82,7 +83,8 @@ public class ResultsController extends HcyBaseController {
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR); //todo
throw new CustomException("导出Excel失败请联系网站管理员");
} }
} }

View File

@ -1,5 +1,7 @@
package com.hchyun.test.controller; package com.hchyun.test.controller;
import com.hchyun.common.core.entity.AjaxResult;
import com.hchyun.test.MapExcelUtil;
import com.hchyun.test.dao.ResultsDao; import com.hchyun.test.dao.ResultsDao;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -21,7 +23,8 @@ public class Test {
private ResultsDao resultsDao; private ResultsDao resultsDao;
@GetMapping("/map") @GetMapping("/map")
public List<Map<String,Object>> mapTest(){ public AjaxResult mapTest(){
return resultsDao.testMap(); MapExcelUtil util = new MapExcelUtil();
return util.exportExcel(resultsDao.testMap(),"test");
} }
} }

View File

@ -18,7 +18,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="testMap" resultType="java.util.HashMap"> <select id="testMap" resultType="java.util.HashMap">
select * from sys_menu select id, uq_id as '父id', uc_name as '名称',
uc_key as '关键字', uc_con as '条件',
uc_mock as '模拟数据', uc_describe as '描述',
uc_type as '控件类型', type as '显示类型' from gen_uni_con
</select> </select>
<select id="selectResultsList" parameterType="Results" resultMap="ResultsResult"> <select id="selectResultsList" parameterType="Results" resultMap="ResultsResult">