java poi 导入导出

Wesley13
• 阅读 639

导入excel

不上传文件到服务器

@RequestMapping(value = "intoDatabases")
@ResponseBody
public Map<String, Object> intoDatabases(
        HttpServletRequest request,
        MultipartFile file)
        throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();
    if (file.isEmpty()) {
        map.put("message", "文件错误,无法读取,请重试!");
        map.put("status", "error");
        map.put("icon", "5");
    } else {
        map = numberService.intoDatabases(file.getInputStream(),
SessionUtils.getUserSession(request));
    }

    return map;
}


public Map<String, Object> intoDatabases(InputStream inputStream, UserSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);//接收到的报表对象
            HSSFSheet sheet = workbook.getSheetAt(0);
            //获得当前sheet的结束行
            int lastRowNum = sheet.getLastRowNum();
  //       System.out.println(lastRowNum);
            List<Number> numbers = new ArrayList<Number>();
            for (int i = 1; i <= lastRowNum; i++) {
                HSSFRow row = sheet.getRow(i);
                Number number = new Number();
                String city = getStringCellValue(row.getCell(2));//城市
                numbers.add(number);
            }

            //存储所有的号码
            numberMapper.batchInsert(numbers);

            //插入记录表
            List<ImportRecord> list = new ArrayList<ImportRecord>();

            for (String key : cityNumber.keySet()) {
                ImportRecord importRecord = new ImportRecord();
                importRecord.setBatch(batch);//批次
                importRecord.setCityId(key);//城市id
                importRecord.setCityName(areaMap.get(key));//城市名称
                importRecord.setCount(cityNumber.get(key));//总数量
                importRecord.setAdminId(session.getAdminId());//导入人
                importRecord.setAdminName(session.getAdminName());//管理员名称
                list.add(importRecord);
            }

            importRecordMapper.batchInsert(list);

            map.clear();
            map.put("message", "操作成功");
            map.put("status", "success");
            map.put("icon", "6");
        } catch (Exception e) {
            map.put("message", "操作失败");
            map.put("status", "error");
            map.put("icon", "5");
            e.printStackTrace();
        }

        return map;
    }

上传文件到服务器

@RequestMapping(value = "importMarkerUnsubscribable")
@ResponseBody
public Map<String, Object> importMarkerUnsubscribable(
        HttpServletRequest request,
        MultipartFile file)
        throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();
    if (file.isEmpty()) {
        map.put("message", "文件错误,无法读取,请重试!");
        map.put("status", "error");
        map.put("icon", "5");
    } else {
String filename = file.getOriginalFilename();
String realPath = request.getSession().getServletContext()
        .getResource("/").getPath();
FileUtils.copyInputStreamToFile(file.getInputStream(),
        new File(realPath, file.getOriginalFilename()));
UserSession session = SessionUtils.getUserSession(request);

        map = numberService.importMarkerUnsubscribable(realPath + filename, session );
    }
    return map;
}

public Map<String, Object> importMarkerUnsubscribable(String filePath, UserSession session) {

    Map<String, Object> map = new HashMap<String, Object>();
    HSSFWorkbook workbook = null;//接收到的报表对象
    InputStream inputStream;
    try {
        inputStream = new FileInputStream(filePath);
        workbook = new HSSFWorkbook(inputStream);
        HSSFSheet sheet = workbook.getSheetAt(0);
        //获得当前sheet的结束行
        int lastRowNum = sheet.getLastRowNum();
        String[] numbers = new String[lastRowNum];
        for (int i = 1; i <= lastRowNum; i++) {
            HSSFRow row = sheet.getRow(i);
            numbers[i - 1] = getStringCellValue(row.getCell(0));
        }
        File file = new File(filePath);
        file.delete();

        map.put("numbers", numbers);
        if (numbers.length > 0) {
            //
            applyListMapper.markerUnsubscribable(map);

        }
        map.clear();
        map.put("message", "标记可退订成功");
        map.put("status", "success");
        map.put("icon", "6");
        return map;

    } catch (Exception e) {
        map.put("message", "操作失败");
        map.put("status", "error");
        map.put("icon", "5");
        e.printStackTrace();
    }
    return null;
}

导出excel

<a class="btn btn-success" href="${ctx}/number/downloadAllNumber">下载全部号码</a>

location.href = "${ctx}/number/downloadNumbers?id=" + row.id + "&type=1";

/**
 * @param req
 * @param res
 * @description 下载申请号码
 * @author GUOPENG
 * @date 2019.04.17
 */
@RequestMapping(value = "downloadNumbers")
public void downloadApplyNumbers(
      HttpServletRequest req,
      HttpServletResponse res,
      @RequestParam(value = "id") String id,
      @RequestParam(value = "type") Integer type) {
   numberService.downloadNumbers(req, res, id, type);
}

@Override
public void downloadNumbers(
        HttpServletRequest request,
        HttpServletResponse res,
        String id, Integer type) {

    OutputStream ouputStream = null;
    HSSFWorkbook workbook = null;// 接收到的报表对象
    InputStream inputStream;
    try {
        String path = request.getSession().getServletContext()
                .getResource("/").getPath() + "下载号码-员工列表.xls";

        inputStream = new FileInputStream(path);
        workbook = new HSSFWorkbook(inputStream);
        HSSFSheet sheet = workbook.getSheetAt(0);
        List<Number> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<String, Object>();
        String batch = "", cityName ="";
        if(type == 1){
            //员工
            ImportRecord importRecord = importRecordMapper.findById(id);
            batch = importRecord.getBatch();
            cityName = importRecord.getCityName();
            map.put("batch", batch);
            map.put("cityId", importRecord.getCityId());
            list = numberMapper.findByBatchCityId(map);
        } else if (type == 2){
            //渠道商
            ApplyRecord applyRecord = applyRecordMapper.findById(id);
            batch = applyRecord.getBatch();
            cityName = applyRecord.getCityName();
            map.put("applyId", id);
            map.put("type", 1);
            list = numberMapper.findByUseApplyId(map);
        }
        for (int i = 1; i <= list.size(); i++) {
            Number number = list.get(i - 1);
            HSSFRow row = sheet.createRow(i);
            row.createCell(0).setCellValue(number.getCity());//地区
            row.createCell(1).setCellValue(number.getNumber());//号码明细
            row.createCell(2).setCellValue(number.getAreaCode());//区号
            row.createCell(3).setCellValue(number.getImsi());//IMSI
            row.createCell(4).setCellValue(number.getSmsc());//短信中心
            row.createCell(5).setCellValue(number.getRemarks());//备注
        }
        res.setContentType("application/vnd.ms-excel;");
        res.setHeader("Content-disposition", "attachment;filename=" + new String((batch+"-"+cityName+".xls").getBytes("GB2312"), "ISO8859_1"));// 设定输出文件头
        ouputStream = res.getOutputStream();
        workbook.write(ouputStream);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

此博客仅供参考使用。

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
3年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这