JAVA实现导出EXCEL

JAVA实现导出EXCEL

之前写过一篇文章 EasyExcel通过模板导出数据
发现一些问题导致无法在服务器上下载excel,问题显示好像是与easyExcel 和 POI Excel 有关,目测是版本,我研究的大半天也没搞出来,就换了一个方法,稳稳的。

注: 这里我使用的是HSSFWorkbook 支持.xls
		如果大伙希望支持.xlsx 请将 HSSFWorkbook换成XSSFWorkbook即可
		欢迎交流心得,互帮互助,共同进步
    /**计划拜访EXCEL*/
    @GetMapping("/excel/route-planning-store")
    public void exportRoutePlanningStore1(HttpServletResponse response,
                                         @RequestParam(value = "organize_ids",required = true) List organizeIds,
                                         @RequestParam(value = "start_time",required = true) String startTime,
                                         @RequestParam(value = "end_time",required = true) String endTime ) throws IOException {

        List param = planVisitDataService.getRoutePlanningStore(organizeIds,startTime,endTime);
        planVisitDataService.exportRoutePlanningStore(param,response);

    }
    @Override
    public void exportRoutePlanningStore(List storelist, HttpServletResponse response) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("templates/计划拜访导入模板.xls");
        InputStream inputStream = classPathResource.getInputStream();
        ExportRoutePlanningStoreUtils utils = new ExportRoutePlanningStoreUtils();
        utils.exportExcel(inputStream, response, storelist);
    }

public class ExportRoutePlanningStoreUtils {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Autowired
    private PlanVisitDataService planVisitDataService;

    //声明一个该工具类的静态的内部对象
    private static ExportRoutePlanningStoreUtils excelUtils;

    @PostConstruct
    public void init() {
        excelUtils = this;
        excelUtils.planVisitDataService =  this.planVisitDataService;
    }

    /**
     *tempPath 模板文件路径
     *path 文件路径
     *list 集合数据
     */
    public void exportExcel(InputStream is, HttpServletResponse response, List storelist) {

        HSSFWorkbook workbook = null;
        HSSFSheet sheet = null;
        try {
            //is = new FileInputStream(newFile);// 将excel文件转为输入流
            workbook =new HSSFWorkbook(is);
            // 获取第一个sheet
            sheet = workbook.getSheetAt(0);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        if (sheet != null) {
            try {
                // 写数据
                //FileOutputStream fos = new FileOutputStream();
                HSSFRow row = sheet.getRow(0);
                if (row == null) {
                    row = sheet.createRow(0);
                }
                HSSFCell cell = row.getCell(0);
                if (cell == null) {
                    cell = row.createCell(0);
                }
                // cell.setCellValue("计划拜访数据");

                List list = getDate(storelist);
                for (int i = 0; i < list.size(); i++) {
                    RoutePlanningStoreParam param = list.get(i);
                    //从第5行开始
                    row = sheet.createRow(i+4);
                    //根据excel模板格式写入数据....
                    createRowAndCell("".equals(param.getDate())?"":param.getDate(), row, cell, 0);
                    createRowAndCell("".equals(param.getSalesId())?"":param.getSalesId(), row, cell, 1);
                    createRowAndCell("".equals(param.getSalesName())?"":param.getSalesName(), row, cell, 2);
                    createRowAndCell("".equals(param.getStoreNo())?"":param.getStoreNo(), row, cell, 3);
                    createRowAndCell("".equals(param.getSalesName())?"":param.getStoreName(), row, cell, 4);
                    createRowAndCell("".equals(param.getMsg())?"":param.getMsg(), row, cell, 5);
                }


                // 通过浏览器 下载
                response.reset();
                response.setContentType("text/html;charset=UTF-8");
                response.setContentType("application/x-msdownload");
                Date currentTime = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                String dateString = formatter.format(currentTime);
                String newName = URLEncoder.encode( "计划拜访" +"_"+  dateString + ".xls", "UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=\"" + newName + "\"");
                workbook.write(response.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != is) {
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     *根据当前row行,来创建index标记的列数,并赋值数据
     */
    private void createRowAndCell(Object obj, HSSFRow row, HSSFCell cell, int index) {
        cell = row.getCell(index);
        if (cell == null) {
            cell = row.createCell(index);
        }

        if (obj != null){
            cell.setCellValue(obj.toString());
        }
        else
        {
            cell.setCellValue("");
        }
    }

    /**
     * 复制文件
     *
     * @param s
     *            源文件
     * @param t
     *            复制到的新文件
     */

    public void fileChannelCopy(File s, File t) {
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(s), 1024);
                out = new BufferedOutputStream(new FileOutputStream(t), 1024);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取excel模板,并复制到新文件中供写入和下载
     *
     * @return
     */
    public File createNewFile(String tempPath, String rPath) {
        // 读取模板,并赋值到新文件************************************************************
        // 文件模板路径
        String path = (tempPath);
        File file = new File(path);
        // 保存文件的路径
        String realPath = rPath;
        // 新的文件名
        String newFileName = System.currentTimeMillis() + ".xls";
        // 判断路径是否存在
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 写入到新的excel
        File newFile = new File(realPath, newFileName);
        try {
            newFile.createNewFile();
            // 复制模板到新文件
            fileChannelCopy(file, newFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFile;
    }



    private List getDate(List storelist) {
        List params = Lists.newArrayList();

        //获取拜访人账号(业代),用于后续升序排列
        Set salesSet = new HashSet<>();
        for (RoutePlanningStoreVo store : storelist) {
            RoutePlanningStore planningStore = store.getRoutePlanningStore();
            if (null != planningStore) {
                salesSet.add(planningStore.getSalesId());
            }
        }

        try {
            //封装数据
            if (null != storelist && CollectionUtils.isNotEmpty(storelist)) {
                for (String id : salesSet) {
                    for (RoutePlanningStoreVo storeVo : storelist) {

                        StringBuffer dataBuf = new StringBuffer();
                        String data = dataBuf.append(storeVo.getYear()).append("/").append(storeVo.getMonth()).append("/").append(storeVo.getDay()).toString();

                        RoutePlanningStore planningStore = storeVo.getRoutePlanningStore();

                        if (null != planningStore) {
                            if (null != id && id.equals(planningStore.getSalesId())) {
                                params = setDataParam(params, data, planningStore);
                            }
                            if (null == id) {
                                params = setDataParam(params, data, planningStore);
                            }
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;

    }

    private List setDataParam(List params, String data, RoutePlanningStore planningStore) {
        List routeStoreList = planningStore.getRouteStores();
        if (null != routeStoreList && CollectionUtils.isNotEmpty(routeStoreList)) {
            for (RouteStore routeStore : routeStoreList) {
                RoutePlanningStoreParam routePlanningStoreParam = new RoutePlanningStoreParam();
                routePlanningStoreParam.setDate(data);
                routePlanningStoreParam.setSalesId(planningStore.getSalesId());
                routePlanningStoreParam.setSalesName(planningStore.getSalesName());
                routePlanningStoreParam.setStoreNo(routeStore.getStoreNo());
                routePlanningStoreParam.setStoreName(routeStore.getStoreName());
                routePlanningStoreParam.setMsg(routeStore.getMsg());
                params.add(routePlanningStoreParam);
            }
        }
        return params;
    }

你可能感兴趣的:(POI,excel,excel,java)