bd8ae48c5a65d1dbaff10499fea16c374fba4950.svn-base 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package cn.com.goldenwater.dcproj.utils;
  2. import cn.com.goldenwater.dcproj.annotation.ExcelImport;
  3. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  4. import org.apache.poi.ss.usermodel.*;
  5. import org.springframework.web.multipart.MultipartFile;
  6. import javax.servlet.http.HttpServletResponse;
  7. import java.io.IOException;
  8. import java.lang.reflect.*;
  9. import java.math.BigDecimal;
  10. import java.net.URLEncoder;
  11. import java.util.*;
  12. import java.util.stream.Collectors;
  13. public class ImportUtil<T> {
  14. /**
  15. * 解析导入文件 MultipartFile -> List<T>
  16. * @param f 导入文件
  17. * @return List<T>
  18. * @throws IOException
  19. */
  20. public List fileToList(MultipartFile f, Class c) throws Exception {
  21. Map<String, Integer> titleMap = new HashMap<>(); // k:表头中文 v:第几列
  22. Map<String, Integer> fieldMap = new HashMap<>(); // k:字段名 v:第几列
  23. List<T> result = new ArrayList<>();
  24. Workbook wb = new HSSFWorkbook(f.getInputStream());
  25. Sheet sheet = wb.getSheetAt(0);
  26. Row row = sheet.getRow(0); // 表头行
  27. for (int i = 0; i < 99; i++) {
  28. Cell cell = row.getCell(i);
  29. if(cell == null) { break; }
  30. String cellValue = cell.getStringCellValue().trim();
  31. if(cellValue == null || "".equals(cellValue)) { break; }
  32. titleMap.put(row.getCell(i).getStringCellValue(), i);
  33. }
  34. List<Field> fields = new ArrayList<>();
  35. Class superclass = c.getSuperclass();
  36. if (superclass != null) {
  37. List<Field> superFields = Arrays.asList(superclass.getDeclaredFields());
  38. List<Field> thisFields = Arrays.asList(c.getDeclaredFields());
  39. fields.addAll(superFields);
  40. fields.addAll(thisFields);
  41. } else {
  42. fields = Arrays.asList(c.getDeclaredFields());
  43. }
  44. for (int i = 0; i < fields.size(); i++) {
  45. ExcelImport annotation1 = fields.get(i).getAnnotation(ExcelImport.class);
  46. if(annotation1 != null && annotation1.isImport()) {
  47. Integer columNum = titleMap.get(annotation1.titleName());
  48. if(columNum != null) {
  49. fieldMap.put(fields.get(i).getName(), columNum);
  50. }
  51. }
  52. }
  53. for (int i = 1; i < 9999; i++) {
  54. T t = (T)c.newInstance();
  55. before(t);
  56. Row r = sheet.getRow(i);
  57. if(r == null || r.getCell(0) == null) { break; }
  58. double cell0DoubleValue = 0;
  59. String cell0StringValue = null;
  60. try {cell0DoubleValue = r.getCell(0).getNumericCellValue();} catch(Exception e) {}
  61. try {cell0StringValue = r.getCell(0).getStringCellValue();} catch(Exception e) {}
  62. if(cell0DoubleValue == 0 && (cell0StringValue == null || "".equals(cell0StringValue))) { break; }
  63. Set<Map.Entry<String, Integer>> entries = fieldMap.entrySet();
  64. for (Map.Entry<String, Integer> entry : entries) {
  65. Cell cell = r.getCell(entry.getValue());
  66. if(cell == null) { continue; }
  67. Field field;
  68. try {
  69. try {
  70. field = c.getDeclaredField(entry.getKey());
  71. } catch (NoSuchFieldException e) {
  72. field = c.getSuperclass().getDeclaredField(entry.getKey());
  73. }
  74. if (field != null) {
  75. field.setAccessible(true);
  76. Class<?> type = field.getType();
  77. if (type == String.class) {
  78. String cellValue = cell.getStringCellValue();
  79. ExcelImport annotation = field.getAnnotation(ExcelImport.class);
  80. if(annotation != null) {
  81. int subStringLength = annotation.subString();
  82. if(subStringLength != -1 && cellValue != null) {
  83. cellValue = cellValue.substring(0, subStringLength);
  84. }
  85. }
  86. field.set(t, cellValue);
  87. } else if (type == Integer.class ) {
  88. field.set(t, (int)cell.getNumericCellValue());
  89. } else if (type == Double.class){
  90. field.set(t, cell.getNumericCellValue());
  91. } else if (type == Long.class){
  92. field.set(t, (long)cell.getNumericCellValue());
  93. } else if (type == BigDecimal.class){
  94. field.set(t, BigDecimal.valueOf(cell.getNumericCellValue()));
  95. } else if (type == Float.class){
  96. field.set(t, (float)cell.getNumericCellValue());
  97. } else if (type == Short.class){
  98. field.set(t, (short)cell.getNumericCellValue());
  99. } else if (type == Date.class){
  100. field.set(t, cell.getDateCellValue());
  101. } else if (type == Boolean.class) {
  102. String v = cell.getStringCellValue();
  103. if (Arrays.asList("是","1","true").contains(v)) {
  104. field.set(t, true);
  105. } else {
  106. field.set(t, false);
  107. }
  108. }
  109. }
  110. } catch (Exception e) {}
  111. }
  112. after(t);
  113. result.add(t);
  114. }
  115. return result;
  116. }
  117. public void before(T t){};
  118. public void after(T t){};
  119. /**
  120. * 导出excel
  121. * @param list
  122. * @param c
  123. * @return
  124. * @throws NoSuchMethodException
  125. * @throws InvocationTargetException
  126. * @throws IllegalAccessException
  127. */
  128. public Workbook export(List<T> list, Class c) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  129. List<Field> declaredFields = new ArrayList<>();
  130. Class superclass = c.getSuperclass();
  131. if (superclass != null) {
  132. List<Field> superFields = Arrays.asList(superclass.getDeclaredFields());
  133. List<Field> thisFields = Arrays.asList(c.getDeclaredFields());
  134. declaredFields.addAll(superFields);
  135. declaredFields.addAll(thisFields);
  136. } else {
  137. declaredFields = Arrays.asList(c.getDeclaredFields());
  138. }
  139. List<Field> sortedList = declaredFields.stream()
  140. .filter(a -> {
  141. return a.getAnnotation(ExcelImport.class) != null;
  142. })
  143. .filter(b -> {
  144. return b.getAnnotation(ExcelImport.class).isExport();
  145. })
  146. .sorted(Comparator.comparing(a -> a.getAnnotation(ExcelImport.class).order()))
  147. .collect(Collectors.toList());
  148. Workbook workbook = new HSSFWorkbook();
  149. Sheet sheet = workbook.createSheet();
  150. Row titleRow = sheet.createRow(0);
  151. for (int i = 0; i < sortedList.size(); i++) {
  152. titleRow.createCell(i).setCellValue(sortedList.get(i).getAnnotation(ExcelImport.class).titleName());
  153. sheet.setColumnWidth(i, sortedList.get(i).getAnnotation(ExcelImport.class).width() * 256);
  154. }
  155. DataFormat dataFormat = workbook.createDataFormat();
  156. CellStyle dateCellStyle = workbook.createCellStyle();
  157. dateCellStyle.setDataFormat(dataFormat.getFormat("yyyy年m月d日"));
  158. for (int i = 0; i < list.size(); i++) {
  159. Row rowi = sheet.createRow(i + 1);
  160. for (int j = 0; j < sortedList.size(); j++) {
  161. Cell cell = rowi.createCell(j);
  162. Field field = sortedList.get(j);
  163. String key = field.getName();
  164. String methordName = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);
  165. Method m = c.getMethod(methordName, null);
  166. if (field.getType() == String.class) {
  167. String cellValue = (String)m.invoke(list.get(i), null);
  168. if (cellValue != null) { cell.setCellValue(cellValue); }
  169. } else if (field.getType() == Integer.class) {
  170. Integer cellValue = (Integer)m.invoke(list.get(i), null);
  171. if (cellValue != null) { cell.setCellValue(cellValue); }
  172. } else if (field.getType() == Double.class) {
  173. Double cellValue = (Double)m.invoke(list.get(i), null);
  174. if (cellValue != null) { cell.setCellValue(cellValue); }
  175. } else if (field.getType() == Date.class){
  176. Date cellValue = (Date)m.invoke(list.get(i), null);
  177. cell.setCellStyle(dateCellStyle);
  178. if (cellValue != null) { cell.setCellValue(cellValue); }
  179. } else if (field.getType() == Long.class) {
  180. Long cellValue = (Long)m.invoke(list.get(i), null);
  181. if (cellValue != null) { cell.setCellValue(cellValue); }
  182. }
  183. }
  184. }
  185. return workbook;
  186. }
  187. /**
  188. * Workbook放入response
  189. * @param wb
  190. * @param response
  191. */
  192. public void buildResponse(Workbook wb, String fileName, HttpServletResponse response) throws IOException {
  193. response.reset();
  194. response.setContentType("application/octet-stream; charset=UTF-8");
  195. response.setCharacterEncoding("utf-8");
  196. response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
  197. wb.write(response.getOutputStream());
  198. }
  199. }