| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731 |
- package cn.com.goldenwater.dcproj.utils.expExcel;
- import cn.com.goldenwater.dcproj.annotation.NotExport;
- import cn.com.goldenwater.dcproj.model.TacExprRcmm;
- import cn.com.goldenwater.dcproj.model.TacWorkerB;
- import cn.com.goldenwater.dcproj.utils.impexcel.ExportExcel;
- import io.swagger.annotations.ApiModelProperty;
- import org.apache.commons.collections.map.HashedMap;
- import org.apache.commons.lang3.ArrayUtils;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.ss.usermodel.*;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
- import org.springframework.web.multipart.MultipartFile;
- import javax.servlet.http.HttpServletResponse;
- import java.io.*;
- import java.lang.reflect.Field;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import static cn.com.goldenwater.dcproj.utils.BeanUtil.transBean2Map;
- /**
- * Created by jinshui on 2019/8/26.
- */
- public class ExportUtil {
- private static final String XLS = "xls";
- private ExportUtil() {
- }
- public static final List<String> COMMONLIST_AND_OPEN_ANNOTATION = new ArrayList<String>() {{
- add("id");
- }};
- private static List<String> list = new ArrayList<>();
- private static List<String> statList = new ArrayList<>();
- static {
- list.add("code");
- list.add("nodeId");
- list.add("ptype");
- list.add("lgtd");
- list.add("lttd");
- list.add("gdX");
- list.add("gdY");
- list.add("objId");
- list.add("id");
- list.add("rgstrId");
- list.add("wintCode");
- list.add("pcX");
- list.add("pcY");
- list.add("safetyStat");
- list.add("measuresStat");
- list.add("waterStat");
- list.add("intInfoStat");
- list.add("apprInfoStat");
- }
- /**
- * 导出所选字段
- *
- * @param result
- * @param response
- * @param fileName
- * @param list
- */
- public static void exportExcelColumn(List<?> result, HttpServletResponse response, String fileName,
- List<String> list, Class cla) {
- if (list == null || list.size() == 0) {
- exportExcel(result, response, fileName);
- return;
- }
- List<Map<String, Object>> mapList = new ArrayList<>();
- result.forEach(worker -> mapList.add(transObjToMap(worker)));
- ExportAbstract export = new ExcelExport();
- if (StringUtils.isBlank(fileName)) {
- fileName = "结果列表";
- }
- export.setFileName(fileName);
- export.setExport_ps_export(true);
- export.setExport_ps_type(ExportAbstract.XLS);
- export.setExport_bzip(false);
- export.setTitle(fileName);
- ArrayList<Object> cols = new ArrayList<Object>();
- Field[] fields = cla.getDeclaredFields();
- for (int j = 0; j <= fields.length - 1; j++) {
- //设置可访问
- Field field = fields[j];
- if (!list.contains(field.getName())) {
- continue;
- }
- field.setAccessible(true);
- if (field.getAnnotation(ApiModelProperty.class) != null) {
- cols.add(field.getName() + "[" + fileFormat(field.getAnnotation(ApiModelProperty.class).value()) + "]");
- }
- }
- if (cols.size() < 1) {
- cols.add("name[名称]");
- cols.add("code[编码]");
- }
- export.setCols(cols);
- export.setGroupable(false);
- // 设置视图指标
- export.setLevel(1);
- export.setLocksize(0);
- try {
- export.Export(response);
- export.ExportHeadForCustom(response);//导出表头
- export.ContinueExport(mapList);
- export.EndExport();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private static Map<String, Object> transObjToMap(Object worker) {
- Map<String, Object> map = new HashedMap();
- Field[] fields = worker.getClass().getDeclaredFields();
- for (int j = 0; j <= fields.length - 1; j++) {
- //设置可访问
- Field field = fields[j];
- field.setAccessible(true);
- field.getName();
- try {
- if (field.getType() == String.class) {
- map.put(field.getName(), String.valueOf(field.get(worker)));
- } else {
- map.put(field.getName(), field.get(worker));
- }
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- return map;
- }
- /**
- * 过滤字段
- *
- * @param result
- * @param response
- * @param fileName
- * @param list
- */
- public static void exportExcel(List<?> result, HttpServletResponse response, String fileName, List<String> list, Class cla) {
- if (list == null || list.size() == 0) {
- exportExcel(result, response, fileName);
- return;
- }
- List<Map<String, Object>> mapList = new ArrayList<>();
- result.forEach(worker -> mapList.add(transBean2Map(worker)));
- ExportAbstract export = new ExcelExport();
- if (StringUtils.isBlank(fileName)) {
- fileName = "结果列表";
- }
- export.setFileName(fileName);
- export.setExport_ps_export(true);
- export.setExport_ps_type(ExportAbstract.XLS);
- export.setExport_bzip(false);
- export.setTitle(fileName);
- ArrayList<Object> cols = new ArrayList<Object>();
- Field[] fields = cla.getDeclaredFields();
- Class clazz = cla.getSuperclass();
- if (clazz != null && clazz != Objects.class) {
- fields = ArrayUtils.addAll(fields, clazz.getDeclaredFields());
- }
- for (int j = 0; j <= fields.length - 1; j++) {
- //设置可访问
- Field field = fields[j];
- if (list.contains(field.getName())) {
- continue;
- }
- field.setAccessible(true);
- if (field.getAnnotation(ApiModelProperty.class) != null && field.getAnnotation(NotExport.class) == null) {
- cols.add(field.getName() + "[" + fileFormat(field.getAnnotation(ApiModelProperty.class).value()) + "]");
- }
- }
- if (cols.size() < 1) {
- cols.add("name[名称]");
- cols.add("code[编码]");
- }
- export.setCols(cols);
- export.setGroupable(false);
- // 设置视图指标
- export.setLevel(1);
- export.setLocksize(0);
- try {
- export.Export(response);
- // 导出表头
- export.ExportHeadForCustom(response);
- export.ContinueExport(mapList);
- export.EndExport();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 使用字段
- *
- * @param result
- * @param response
- * @param fileName
- * @param list
- */
- public static void exportExcel2(List<?> result, HttpServletResponse response, String fileName, List<String> list, Class cla) {
- if (list == null || list.size() == 0) {
- exportExcel(result, response, fileName);
- return;
- }
- List<Map<String, Object>> mapList = new ArrayList<>();
- result.forEach(worker -> mapList.add(transBean2Map(worker)));
- ExportAbstract export = new ExcelExport();
- if (StringUtils.isBlank(fileName)) {
- fileName = "结果列表";
- }
- export.setFileName(fileName);
- export.setExport_ps_export(true);
- export.setExport_ps_type(ExportAbstract.XLS);
- export.setExport_bzip(false);
- export.setTitle(fileName);
- ArrayList<Object> cols = new ArrayList<Object>();
- Field[] fields = cla.getDeclaredFields();
- Class clazz = cla.getSuperclass();
- if (clazz != null && clazz != Objects.class) {
- fields = ArrayUtils.addAll(fields, clazz.getDeclaredFields());
- }
- for (String name : list) {
- for (Field field : fields) {
- if (name.equals(field.getName()) && field.getAnnotation(ApiModelProperty.class) != null) {
- field.setAccessible(true);
- cols.add(field.getName() + "[" + fileFormat(field.getAnnotation(ApiModelProperty.class).value()) + "]");
- break;
- }
- }
- }
- if (cols.size() < 1) {
- cols.add("name[名称]");
- cols.add("code[编码]");
- }
- export.setCols(cols);
- export.setGroupable(false);
- // 设置视图指标
- export.setLevel(1);
- export.setLocksize(0);
- try {
- export.Export(response);
- // 导出表头
- export.ExportHeadForCustom(response);
- export.ContinueExport(mapList);
- export.EndExport();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static String fileFormat(String value) {
- if (isContainNum(value)) {
- return value;
- }
- //统一字符处理
- value = value.replace("(", "(");
- if (value.contains(" ")) {
- value = value.substring(0, value.indexOf(" "));
- }
- if (value.contains("(")) {
- value = value.substring(0, value.indexOf("("));
- }
- if (value.startsWith("*")) {
- value = value.substring(1);
- }
- return value;
- }
- private static boolean isContainNum(String value) {
- if (value.contains("m3")) {
- return true;
- }
- if (value.contains("km2")) {
- return true;
- }
- return false;
- }
- public static void exportExcel(List<?> result, HttpServletResponse response, String fileName) {
- List<Map<String, Object>> mapList = new ArrayList<>();
- ExportAbstract export = new ExcelExport();
- if (StringUtils.isBlank(fileName)) {
- fileName = "结果列表";
- }
- export.setFileName(fileName);
- export.setExport_ps_export(true);
- export.setExport_ps_type(ExportAbstract.XLS);
- export.setExport_bzip(false);
- export.setTitle(fileName);
- ArrayList<Object> cols = new ArrayList<Object>();
- boolean flag = true;
- for (Object o : result) {
- mapList.add(transBean2Map(o));
- if (flag) {
- Field[] fields = o.getClass().getDeclaredFields();
- for (int j = 0; j <= fields.length - 1; j++) {
- //设置可访问
- Field field = fields[j];
- if (list.contains(field.getName())) {
- continue;
- }
- field.setAccessible(true);
- if (field.getAnnotation(ApiModelProperty.class) != null) {
- cols.add(field.getName() + "[" + field.getAnnotation(ApiModelProperty.class).value() + "]");
- }
- }
- flag = false;
- }
- }
- if (cols.size() < 1) {
- cols.add("name[名称]");
- cols.add("code[编码]");
- cols.add("location[地址]");
- cols.add("adCode[行政区划编码]");
- }
- export.setCols(cols);
- export.setGroupable(false);
- // 设置视图指标
- export.setLevel(1);
- export.setLocksize(0);
- try {
- export.Export(response);
- //导出表头
- export.ExportHeadForCustom(response);
- export.ContinueExport(mapList);
- export.EndExport();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void exportExcel(String isExport, List<?> result, HttpServletResponse response) {
- if ("1".equals(isExport)) {
- exportExcel(result, response, "");
- }
- }
- /**
- * 返回某个类需要导出的字段列表
- *
- * @param cla
- * @param list
- */
- public static List<Map<String, Object>> getExoportColumns(Class cla, List<String> list) {
- List<Map<String, Object>> cols = new ArrayList<>();
- Field[] fields = cla.getDeclaredFields();
- for (int j = 0; j <= fields.length - 1; j++) {
- //设置可访问
- Field field = fields[j];
- if (list.contains(field.getName())) {
- continue;
- }
- field.setAccessible(true);
- if (field.getAnnotation(ApiModelProperty.class) != null) {
- Map<String, Object> map = new HashMap<>();
- map.put("code", field.getName());
- String value = field.getAnnotation(ApiModelProperty.class).value().trim();
- //统一字符处理
- value = value.replace("(", "(");
- if (value.contains(" ")) {
- value = value.substring(0, value.indexOf(" "));
- }
- if (value.contains("(")) {
- value = value.substring(0, value.indexOf("("));
- }
- if (value.startsWith("*")) {
- value = value.substring(1);
- map.put("selectFlag", true);
- }
- map.put("name", value);
- cols.add(map);
- }
- }
- return cols;
- }
- /**
- * 根据名称
- *
- * @param value
- * @param name
- * @param b
- */
- public static void setClassFiledValue(Object value, String name, Object b, boolean isFormat) {
- if (name == null) {
- return;
- }
- try {
- Field[] fields = b.getClass().getDeclaredFields();
- for (Field field : fields) {
- field.setAccessible(true);
- if (field.getAnnotation(ApiModelProperty.class) != null) {
- String nameValue = field.getAnnotation(ApiModelProperty.class).value();
- if (isFormat) {
- nameValue = fileFormat(nameValue);
- }
- if (name.equals(nameValue) && StringUtils.isNotBlank(String.valueOf(value))) {
- field.set(b, value);
- }
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static File isExist(String originUrl) throws IOException {
- // 判断文件是否存在
- File file = new File(originUrl);
- if (!file.exists()) {
- throw new IOException("文件名为" + file.getName() + "Excel文件不存在!");
- }
- return file;
- }
- /**
- * 根据字段名称下载Excel
- *
- * @param response
- * @param list
- * @param filePath
- */
- public static void download(HttpServletResponse response, List<Map<String, Object>> list, String filePath) throws IOException {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- FileInputStream fis = new FileInputStream(isExist(filePath));
- String fileExt = filePath.substring(filePath.lastIndexOf(".")).replace(".", "");
- Workbook workBook = null;
- if (XLS.equals(fileExt)) {
- workBook = new HSSFWorkbook(fis);
- } else {
- workBook = new XSSFWorkbook(fis);
- }
- Sheet sheet = workBook.getSheetAt(0);
- Row keyRow = sheet.getRow(1);
- List<String> keys = new ArrayList<>();
- for (int r = 0; r < keyRow.getPhysicalNumberOfCells(); r++) {
- if (!"".equals(keyRow.getCell(r).toString())) {
- keys.add(keyRow.getCell(r).toString());
- }
- }
- Row row = null;
- for (int i = 0; i < list.size(); i++) {
- row = sheet.createRow(i + 2);
- Map<String, Object> map = list.get(i);
- for (int j = 0; j < keys.size(); j++) {
- Object val = map.get(keys.get(j));
- if (val == null) {
- continue;
- }
- if (val.getClass() == Double.class) {
- row.createCell(j).setCellValue((double) val);
- } else if (val.getClass() == Long.class) {
- row.createCell(j).setCellValue((long) val);
- } else {
- row.createCell(j).setCellValue(val == null ? "" : val.toString());
- }
- }
- }
- workBook.write(os);
- fis.close();
- os.flush();
- os.close();
- ExportExcel.downloadExcelFile(response, os, "人员列表" + filePath.substring(filePath.lastIndexOf(".")));
- if (fis != null) {
- fis.close();
- }
- }
- public static Map<String, Object> objToMap(Object obj, boolean isFormat) {
- if (obj == null) {
- return null;
- }
- Map<String, Object> map = new HashedMap();
- Field[] fields = obj.getClass().getDeclaredFields();
- for (int i = 0; i < fields.length; i++) {
- Field field = fields[i];
- field.setAccessible(true);
- if (field.getAnnotation(ApiModelProperty.class) != null) {
- String nameValue = field.getAnnotation(ApiModelProperty.class).value();
- if (isFormat) {
- nameValue = fileFormat(nameValue);
- }
- try {
- map.put(nameValue, field.get(obj));
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- }
- return map;
- }
- public static List<Row> getRowListByFile(MultipartFile file) {
- List<Row> rowList = new ArrayList<>();
- Workbook wb = null;
- try (InputStream fis = file.getInputStream()) {
- if (Objects.requireNonNull(file.getOriginalFilename()).endsWith(XLS)) {
- wb = new HSSFWorkbook(fis);
- } else {
- wb = new XSSFWorkbook(fis);
- }
- Sheet sheet = wb.getSheetAt(0);
- Row row = null;
- int lastRowNum = sheet.getPhysicalNumberOfRows();
- for (int i = sheet.getFirstRowNum(); i < lastRowNum; i++) {
- row = sheet.getRow(i);
- if (row != null) {
- rowList.add(row);
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (wb != null) {
- try {
- wb.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return rowList;
- }
- /**
- * @param rowList 行集合
- * @param i 开始行,一般为名称行数的下表,没有code隐藏行时
- * @return
- */
- public static List<Map<String, Object>> rowToMap(List<Row> rowList, int i) {
- if (i == 0) {
- i = 1;
- }
- List<String> keys = new ArrayList<>();
- Row keyRow = rowList.get(i);
- for (int r = 0; r < keyRow.getPhysicalNumberOfCells(); r++) {
- if (!"".equals(keyRow.getCell(r).toString())) {
- keys.add(keyRow.getCell(r).toString());
- }
- }
- List<Map<String, Object>> mapList = new ArrayList<>();
- Row row = null;
- for (int j = i + 1; j < rowList.size(); j++) {
- row = rowList.get(j);
- Map<String, Object> map = new HashedMap();
- for (int k = 0; k < keys.size(); k++) {
- Cell cell = row.getCell(k);
- if (cell != null) {
- if (cell.getCellType() == CellType.NUMERIC) {
- map.put(keys.get(k), cell.getNumericCellValue());
- } else if (cell.getCellType() == CellType.STRING) {
- map.put(keys.get(k), cell.getStringCellValue());
- }
- }
- }
- mapList.add(map);
- }
- return mapList;
- }
- public static List<TacWorkerB> mapToObj(List<Map<String, Object>> mapList, Class cla, boolean isFormat) {
- if (mapList == null || mapList.size() == 0) {
- return null;
- }
- List<TacWorkerB> list = new ArrayList<>();
- Field[] fields = cla.getDeclaredFields();
- for (Map<String, Object> map : mapList) {
- TacWorkerB workerB = new TacWorkerB();
- for (Field field : fields) {
- field.setAccessible(true);
- if (field.getAnnotation(ApiModelProperty.class) != null) {
- String nameValue = field.getAnnotation(ApiModelProperty.class).value();
- if (isFormat) {
- nameValue = fileFormat(nameValue);
- }
- if (map.containsKey(nameValue)) {
- try {
- Object object = map.get(nameValue);
- if (object == null) {
- continue;
- }
- if (field.getType() == Double.class) {
- field.set(workerB, Double.valueOf(String.valueOf(object)));
- }
- if (field.getType() == String.class) {
- if (object.getClass() == Double.class) {
- if (80000000.0 - (double) object < 0) {
- object = (long) ((double) object);
- object = String.valueOf(object);
- }
- field.set(workerB, object);
- } else {
- field.set(workerB, String.valueOf(object));
- }
- }
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- }
- }
- list.add(workerB);
- }
- return list;
- }
- public static List<Object> mapToObj(List<Map<String, Object>> mapList, Class cla) {
- if (mapList == null || mapList.size() == 0) {
- return null;
- }
- List<Object> list = new ArrayList<>();
- Field[] fields = cla.getDeclaredFields();
- for (Map<String, Object> map : mapList) {
- Object obj = null;
- try {
- obj = cla.newInstance();
- for (Field field : fields) {
- field.setAccessible(true);
- if (field.getAnnotation(ApiModelProperty.class) != null) {
- String nameValue = field.getAnnotation(ApiModelProperty.class).value();
- if (map.containsKey(nameValue)) {
- try {
- Object object = map.get(nameValue);
- if (object == null) {
- continue;
- }
- if (field.getType() == Double.class) {
- field.set(obj, Double.valueOf(String.valueOf(object)));
- }
- if (field.getType() == String.class) {
- field.set(obj, String.valueOf(object));
- }
- if (field.getType() == Date.class) {
- SimpleDateFormat format = new SimpleDateFormat("yyyy/mm/dd");
- try {
- field.set(obj, format.parse(String.valueOf(object)));
- } catch (ParseException e) {
- e.printStackTrace();
- }
- }
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- }
- }
- list.add(obj);
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- return list;
- }
- public static void exportExcel(Map<String, List<TacExprRcmm>> map, HttpServletResponse response, String fileName, List<String> columns) throws IOException {
- // 设置response参数,可以打开下载页面
- response.reset();
- response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
- response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
- Workbook workbook = new XSSFWorkbook();
- if (map != null) {
- for (String sheetName : map.keySet()) {
- Sheet sheet = workbook.createSheet(sheetName);
- createExcelContent(sheet, map.get(sheetName), columns);
- }
- }
- workbook.write(response.getOutputStream());
- workbook.close();
- }
- private static void createExcelContent(Sheet sheet, List<?> tacExprRcmms, List<String> columns) {
- if (tacExprRcmms == null || tacExprRcmms.size() == 0) {
- return;
- }
- boolean flag = false;
- Row titleRow = null;
- Map<Integer, String> columnMap = new HashedMap();
- for (int i = 0; i < tacExprRcmms.size(); i++) {
- Map<String, Object> map = transObjToMap(tacExprRcmms.get(i));
- if (!flag) {
- titleRow = sheet.createRow(1);
- createTitleRow(titleRow, tacExprRcmms.get(i), columnMap, columns);
- }
- if (titleRow == null) {
- continue;
- }
- Row row = sheet.createRow(i + 2);
- row.createCell(0).setCellValue(i + 1);
- for (int j = 1; j < titleRow.getPhysicalNumberOfCells(); j++) {
- row.createCell(j).setCellValue(map.get(columnMap.get(j)) == null ? "" : String.valueOf(map.get(columnMap.get(j))));
- }
- }
- }
- private static void createTitleRow(Row titleRow, Object obj, Map<Integer, String> columnMap, List<String> columns) {
- Field[] fields = obj.getClass().getDeclaredFields();
- titleRow.createCell(0).setCellValue("序号");
- for (int i = 0; i < fields.length; i++) {
- Field field = fields[i];
- if (columns.contains(field.getName())) {
- continue;
- }
- field.setAccessible(true);
- if (field.getAnnotation(ApiModelProperty.class) != null) {
- String nameValue = fileFormat(field.getAnnotation(ApiModelProperty.class).value());
- titleRow.createCell(i + 1).setCellValue(nameValue);
- columnMap.put(i + 1, field.getName());
- }
- }
- }
- }
|