我的导出cvs的功能
CVS是一种字符串的特定形式,可以无限写。
Controller代码:
@ResponseBody @RequestMapping(value = "/export") public Object doExport(HttpServletResponse response, @ModelAttribute("loanbillForm") LoanBillForm loanbillForm) { Map<String, String> resultMap = new HashMap<>(); Map<String, String> loanBillMap = new HashMap<>(); loanBillMap = Bean2MapUtil.beanToMapNoFill(loanbillForm); if (BeanUtil.filedNotNull(loanbillForm.getStartExpireDate())) { loanBillMap.put("startExpireDate", DateUtil.removeLineColonDateTime(loanbillForm.getStartExpireDate())); } if (BeanUtil.filedNotNull(loanbillForm.getEndExpireDate())) { loanBillMap.put("endExpireDate", DateUtil.removeLineColonDateTime(loanbillForm.getEndExpireDate())); } if (BeanUtil.filedNotNull(loanbillForm.getStartValueDate())) { loanBillMap.put("startValueDate", DateUtil.removeLineColonDateTime(loanbillForm.getStartValueDate())); } if (BeanUtil.filedNotNull(loanbillForm.getEndValueDate())) { loanBillMap.put("endValueDate", DateUtil.removeLineColonDateTime(loanbillForm.getEndValueDate())); } if (StringUtils.isNotBlank(loanbillForm.getRepayDateStart())) { loanBillMap.put("repayDateStart", DateUtil.removeLineColonDateTime(loanbillForm.getRepayDateStart()+" 00:00:00")); } if (StringUtils.isNotBlank(loanbillForm.getRepayDateEnd())) { loanBillMap.put("repayDateEnd", DateUtil.removeLineColonDateTime(loanbillForm.getRepayDateEnd()+" 23:59:59")); } CSVExportUtil<LoanBill> excelUtil = new CSVExportUtil<>(); try { loanBillMap.put("pageSize", "1000"); loanBillMap.put("pageCurrent", "1"); int pageCount = loanBillService.countAllLoanBill(loanBillMap); for (int i = 1; i <= pageCount; i++) { loanBillMap.put("pageCurrent", String.valueOf(i)); List<LoanBill> loanBillList = this.loanBillService.selectExportLoanBill(loanBillMap); if (loanBillList.size() == 0) { LoanBill loanBill = new LoanBill(); loanBillList.add(loanBill); } boolean isAppend = true; if (i == 1) { isAppend = false; } excelUtil.buildCVSFile(loanBillList, LoanBill.class, isAppend); } excelUtil.flushToRequest(response, "账单查询"); }catch(Exception e){ logger.info("导出Excel表格失败!"); e.printStackTrace(); } resultMap.put("statusCode", "200"); resultMap.put("message", "导出Excel表格成功!"); return null; }
我的CVSUtils类:
package com.allcheer.acl.omc.util; import com.alibaba.fastjson.util.UTF8Decoder; import com.allcheer.acl.omc.util.enums.ExcelElement; import com.allcheer.acl.omc.util.enums.ExcelFormat; import com.allcheer.acl.omc.util.enums.ExcelSelect; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.nio.cs.ext.GBK; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.util.*; import static org.apache.commons.codec.CharEncoding.UTF_8; /** * Created by zhen on 2017-05-27. */ public class CSVExportUtil<T> { Logger logger = LoggerFactory.getLogger(ExcelUtil.class); private static final String ESCAPE_CHARACTER = "\""; private static final String NEW_LINE = "\r\n"; private static final String LINE_BREAK = ","; private boolean fileNotSuper = false; private File file; public CSVExportUtil() { file = createTmpFile(); } private File createTmpFile() { try { if (file == null) { file = new File("tmp.cvs"); file.createNewFile(); } else { file.delete(); file = new File("tmp.cvs"); file.createNewFile(); } } catch (IOException e) { logger.error("文件初始化失败",e); e.printStackTrace(); } return file; } /** * 替换敏感词 * * @param value * @return */ private String replaceSensitiveWord(String value) { if (value == null) { return value; } value = value.replaceAll("\"", ESCAPE_CHARACTER + "\"" + ESCAPE_CHARACTER); value = value.replaceAll(",", ESCAPE_CHARACTER + "," + ESCAPE_CHARACTER); value = value.replaceAll("\\r\\n", ESCAPE_CHARACTER + "\\r\\n" + ESCAPE_CHARACTER); return value; } /** * @param clazz * @return */ private Map<String, String> getCSVFileMap(Class<T> clazz) { Map<String, String> map = new HashMap<String, String>(); Map<String, String> ret = new LinkedHashMap<String, String>(); Map<Integer, String> order = new HashMap<Integer, String>(); Field[] fields = clazz.getFields(); if (fileNotSuper) { fields = null; } Field[] thisFields = clazz.getDeclaredFields(); fields = unionFields(fields, thisFields); boolean annotationPresent; for (Field f : fields) { if (f == null) { continue; } annotationPresent = f.isAnnotationPresent(ExcelElement.class); if (annotationPresent) { ExcelElement test = f.getAnnotation(ExcelElement.class); map.put(f.getName(), test.field()); order.put(test.index(), f.getName()); } } // 排序 Set<Integer> keySet = order.keySet(); Integer[] array = keySet.toArray(new Integer[keySet.size()]); Arrays.sort(array); for (int i = 0; i < array.length; i++) { String fieldName = order.get(array[i]); String excelFieldName = map.get(fieldName); ret.put(fieldName, excelFieldName); } return ret; } /** * 拼接两个Field[] * * @param fields1 * @param fields2 * @return */ private Field[] unionFields(Field[] fields1, Field[] fields2) { if (fields1 == null) { return fields2; } if (fields2 == null) { return fields1; } Field[] fields = new Field[fields1.length + fields2.length]; System.arraycopy(fields1, 0, fields, 0, fields1.length); System.arraycopy(fields2, 0, fields, fields1.length, fields2.length); return fields; } /** * 格式化值 * * @param t * @param beanFileName * @return * @throws IllegalAccessException * @throws NoSuchMethodException * @throws InvocationTargetException */ private String formatValue(T t, String beanFileName) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { String value = BeanUtils.getSimpleProperty(t, beanFileName); try { Field field = t.getClass().getDeclaredField(beanFileName); boolean annotationPresent = field.isAnnotationPresent(ExcelFormat.class); if (annotationPresent) { ExcelFormat excelFormat = field.getAnnotation(ExcelFormat.class); String dateFormat = excelFormat.dateFormat(); if (dateFormat != null && !"".equals(dateFormat)) { value = DateFormatUtils.format(new Date(value), dateFormat); } } boolean annotationPresent2 = field.isAnnotationPresent(ExcelSelect.class); if (annotationPresent2) { ExcelSelect excelSelect = field.getAnnotation(ExcelSelect.class); String[] select = excelSelect.select(); if (select != null && (select.length % 2 == 0)) { for (int i = 0; i < select.length; i = i + 2) { if (select[i] != null && select[i].equals(value)) { value = select[i + 1]; } } } } } catch (Exception ex) { logger.error("数据格式化异常,使用原数据", ex); } return replaceSensitiveWord(value); } /** * @param ts * @param clazz * @param isAppend * @throws Exception */ public void buildCVSFile(List<T> ts, Class<T> clazz, boolean isAppend) throws Exception { try ( BufferedWriter bos = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, isAppend)))) { if (ts == null) { throw new Exception("export csv failed , data is null"); } Map<String, String> csvFileMap = null; StringBuilder sb; csvFileMap = getCSVFileMap(clazz); //标题行 if (!isAppend) { Object[] ths = csvFileMap.values().toArray(); sb = new StringBuilder(); for (Object th : ths) { sb.append(th.toString()).append(LINE_BREAK); } sb = sb.deleteCharAt(sb.length() - 1); bos.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));//加Bom标记 bos.write(sb.toString()); bos.flush(); } for (T t : ts) { sb = new StringBuilder(); sb = sb.append(NEW_LINE); Iterator<Map.Entry<String, String>> entries = csvFileMap.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); sb.append(formatValue(t, entry.getKey())).append(LINE_BREAK); } sb = sb.deleteCharAt(sb.length() - 1); bos.write(sb.toString()); bos.flush(); } } } /** * @param response * @param fileName * @throws Exception */ public void flushToRequest(HttpServletResponse response, String fileName) throws Exception { if (fileName == null) { fileName = "default"; } try { response.setContentType("text/csv"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/vnd.ms-excel"); fileName = new String(fileName.getBytes("gb2312"), "iso8859-1"); response.setHeader("Content-disposition", String.format("attachment;filename=%s.csv", fileName)); FileInputStream ins=new FileInputStream(file); OutputStream out = response.getOutputStream(); IOUtils.copy(ins, out); out.flush(); ins.close(); out.close(); } catch (Exception e) { logger.error("导出cvs错误:", e); throw e; } finally { file.delete(); } } }

浙公网安备 33010602011771号