Java代码POI导入导出 Excel导入模板下载、导入、导出详解(附代码)

264 阅读3分钟

@Java代码Excel导入模板下载、导入、导出详解(附代码)

Java代码Excel导入模板下载、导入、导出详解(附代码)目录

1、pom文件添加POI依赖; 2、Postman Excel导入模板下载; 3、Excel导入模板下载Java代码详解; 4、Postman Excel导入请求参数; 5、Excel导入Java代码详解; 6、Postman Excel导出请求参数; 7、Excel导出Java代码详解;

1、pom文件添加POI依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.1</version>
</dependency>

2、Postman Excel导入模板下载

输入好请求地址,直接按照图片划红线部分Send and Download即可 输入好请求地址,直接按照图片划红线部分Send and Download即可,Postman会直接下载文件,如果文件为json类型,可能为报错信息。

3、Excel导入模板下载Java代码详解

    public void exportTemplate(HttpServletResponse response) {
        try {
            // 创建Excel表格工作簿
            XSSFWorkbook wb = new XSSFWorkbook();
            //sheet命名
            Sheet sheet = wb.createSheet( "学生信息导入模板" );
            //样式设置
            XSSFCellStyle style = wb.createCellStyle();
            //设置填充方案
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            style.setFillForegroundColor(IndexedColors.LIGHT_ORANGE.getIndex());

            Row row = sheet.createRow(0);
            ArrayList<String> cols = new ArrayList<String>();
            cols.add( "姓名" );
            cols.add( "性别");
            cols.add("学号" );
            cols.add( "年级" );
            for (int i = 0, j = cols.size(); i < j; i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(style);
                cell.setCellType(CellType.STRING);
                cell.setCellValue(cols.get(i));
//                // 设置宽度,自适应 - 开始
                int columnWidth = sheet.getColumnWidth(i) / 256;
                int length = cols.get(i).getBytes("UTF-8").length + 1;
                if (columnWidth < length + 1) {
                    columnWidth = length + 1;
                }
                sheet.setColumnWidth(i, columnWidth * 256);
                // 设置宽度,自适应 - 结束
            }
            //sheet命名
            XSSFSheet tplDesSheet = wb.createSheet( "模板说明" );
            // 设置宽度,自适应 - 开始
            tplDesSheet.setColumnWidth(0, 25000);
            String[] info = new String[]{ "模板的一些说明","注:1、若学号为数字,请设置单元格为文本类型,避免数字省略出错\n2、保持对应关系,避免数据异常" };
            for (int i = 0; i < info.length; i++) {
                XSSFRow tplrow = tplDesSheet.createRow(i);
                Cell tplcell = tplrow.createCell(0);
                // tplcell.setWrap(true);
                if (i == (info.length - 1)) {
                    tplcell.setCellStyle(style);
                }
                tplcell.setCellType(CellType.STRING);
                tplcell.setCellValue(info[i]);
            }
            response.reset();
            //导出表名称,但Postman统一为response,网页上下载会以此命名
            String fileName = "学生信息导入模板" ;
            //设置类型为.xlsx
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //导出表名称,但Postman统一为response,网页上下载会以此命名
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(), "iso-8859-1") + ".xlsx");
            wb.write(response.getOutputStream());
        } catch (Exception e) {
            throw new BusinessRuntimeException("模板导出失败!"  + e.getMessage());
        }
    }

4、Postman Excel导入请求参数;

导入时往往伴随着其他条件参数的传递,按照图中传递方式传递即可,条件参数根据个人需求新增或删减 导入时往往伴随着其他条件参数的传递,按照图中传递方式传递即可,条件参数根据个人需求新增或删减。

5、Excel导入Java代码详解;

    @ControllerRS
    @RequestMapping(value = "importexcel", method = RequestMethod.POST)
    public @ResponseBody
    Object importdzb(@RequestBody MultipartFile file, String condition1, String condition2, String condition3) throws Exception {
        InputStream inputStream = null;
        try {
            //接收文件,其他参数根据实际情况使用接收
            inputStream = file.getInputStream();
            com.alibaba.fastjson.JSONArray dataArray = new com.alibaba.fastjson.JSONArray();
            XSSFWorkbook wb = new XSSFWorkbook(inputStream);
            //取出第一张表,遍历行
            for (int index = 0; index < 1; index++) {
                XSSFSheet sheet = wb.getSheetAt(index);
                Map<Integer, String> keymap = new HashMap<Integer, String>();
                XSSFRow row = null;
                //遍历行
                for (int i = sheet.getFirstRowNum(); i <= sheet.getPhysicalNumberOfRows(); i++) {
                    try {
                        row = sheet.getRow(i);
                    } catch (Exception e) {

                    }
                    // 当读取行为空时
                    if (row == null) {
                        continue;
                    }
                    com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
                    //取出每一行的列数据
                    for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
                        if (i == 0) {//表头栏
                            keymap.put(j, row.getCell(j).getStringCellValue());
                        } else {//数据栏
                            //将每列的表头同每列的数据放入json
                            if (row.getCell(j) != null) {
                                row.getCell(j).setCellType(CellType.STRING);
                                json.put(keymap.get(j), row.getCell(j).getStringCellValue());
                            } else {
                                json.put(keymap.get(j), null);
                            }
                        }
                    }
                    //将每行数据json放入json数组
                    if (json.size() > 0) {
                        dataArray.add(json);
                    }
                }
            }
            //判断dataArray是否有数据,有的话调用importjson方法
            if (dataArray.size() > 0) {
                importjson(dataArray.toJSONString());
            }

        } catch (Exception e) {
            throw new BusinessRuntimeException("数据导入错误:" + e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e1) {
                }
            }
        }

        return true;
    }

    public void importjson(String data) {
        List<String> codeList = new ArrayList<String>();
        try {
            //本段处理将行上数据匹配到对应实体类中,可一条条数据逐个保存,也可将匹配不同实体类放入集合,统一保存,按实际需求选择
            JSONArray ja = JSONArray.fromObject(data);
            if (ja != null && !ja.isEmpty()) {
                //Map<String, ClassMappingVO> map = new HashMap<String, ClassMappingVO>();

                Map<String, String[]> keymap = new HashMap<String, String[]>();
                //遍历表格每一行信息 k表头  v行信息
                for (Object object : ja) {
                    if (object != null && object instanceof JSONObject) {
                      
                        JSONObject js = (JSONObject) object;
                        //获得表头信息集合
                        Set keySet = js.keySet();
                        //遍历表头信息集合,与实体类字段匹配,自己跟据实际情况添加
                        for (Object key : keySet) {
                            Object value = null;
                            String strkey = (String) key;
                            if ("姓名".equals(strkey)) {

                            } else if ("性别".equals(strkey)) {

                            } else if ("学号".equals(strkey)) {

                            } else if ("年级".equals(strkey)) {

                            } else {
                                continue;
                            }
                            //将对应字段值放入实体类中,自己根据实际情况添加
                            
                            
                            
                        }
                    }

                }
            }
        } catch (Throwable e) {
            throw e;
        }

    }

6、Postman Excel导出请求参数

根据id进行批量导出,id为空可设为全部导出 根据id进行批量导出,id为空可设为全部导出

7、Excel导出Java代码详解

    @RequestMapping(value = "/exportTable", method = {RequestMethod.POST, RequestMethod.GET})
    public void exportTable(@RequestParam(value = "data", required = false) String[] data, HttpServletResponse response) {
        //接收的data是一个id数组,根据id进行批量导出,id为空可设为全部导出,依据实际情况而定
        //根据id查询出学生实体类集合
        List<Student> students = new ArrayList<Student>();
        Student student = new Student();
        for (String datum : data) {

        }

        try {
            XSSFWorkbook wb = new XSSFWorkbook();
            //sheet命名
            Sheet sheet = wb.createSheet("学生信息导出数据");
            //样式
            XSSFCellStyle style = wb.createCellStyle();
            //设置填充方案
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            style.setFillForegroundColor(IndexedColors.LIGHT_ORANGE.getIndex());
            //设置表头
            Row row = sheet.createRow(0);
            ArrayList<String> cols = new ArrayList<String>();
            cols.add("姓名");
            cols.add("性别");
            cols.add("学号");
            cols.add("年级");
            for (int i = 0, j = cols.size(); i < j; i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(style);
                cell.setCellType(CellType.STRING);
                cell.setCellValue(cols.get(i));
//                // 设置宽度,自适应 - 开始
                int columnWidth = sheet.getColumnWidth(i) / 256;
                int length = cols.get(i).getBytes("UTF-8").length + 1;
                if (columnWidth < length + 1)
                    columnWidth = length + 1;
                sheet.setColumnWidth(i, columnWidth * 256);
                // 设置宽度,自适应 - 结束
            }
            int n = 1;
            //遍历学生信息实体类集合,分个放入每一行上
            for (Student studentVO : students) {
                //n为递增
                Row row1 = sheet.createRow(n);
                ArrayList<String> cols1 = new ArrayList<String>();
                cols1.add(studentVO.getName());
                cols1.add(studentVO.getSex());
                cols1.add(studentVO.getNumber());
                cols1.add(studentVO.getGrade());

                for (int i = 0, j = cols1.size(); i < j; i++) {
                    Cell cell = row1.createCell(i);
                    //cell.setCellStyle(style);
                    cell.setCellType(CellType.STRING);
                    cell.setCellValue(cols1.get(i));
//                // 设置宽度,自适应 - 开始
                    int columnWidth = sheet.getColumnWidth(i) / 256;
                    int length = cols1.get(i).getBytes("UTF-8").length + 1;
                    if (columnWidth < length + 1)
                        columnWidth = length + 1;
                    sheet.setColumnWidth(i, columnWidth * 256);
                    // 设置宽度,自适应 - 结束
                }
                n++;
            }
            response.reset();
            //导出表名称,但Postman统一为response,网页上下载会以此命名
            String fileName = "学生导出列表";
            //设置类型为.xlsx
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //导出表名称,但Postman统一为response,网页上下载会以此命名
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(), "iso-8859-1") + ".xlsx");
            wb.write(response.getOutputStream());

        } catch (Exception e) {
            throw new BusinessRuntimeException("学生信息导出失败!" + e.getMessage());
        }
    }

此文只是个人导入导出的一种方法,希望对您有所帮助,如有不同见解和疑问,欢迎沟通交流。