• Excel模板下载/导入导出工具类


    环境 :jdk1.8

    maven :3.8.1

    引入jar :

    <!-- Excel 导入导出依赖 start -->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.10-FINAL</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>3.9</version>
            </dependency>
            <!-- Excel 导入导出依赖 end -->

    构建测试 Controller :

    package com...controller;
    
    import com...service.ExcelService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author lifan
     */
    @RestController
    public class ExcelController {
    
        @Autowired
        private ExcelService excelService;
    
        /**
         * 模板下载
         */
        @GetMapping("/v1/dataModelDownload")
        public void insureDataModelDownload(HttpServletResponse response) throws Exception {
            excelService.dataModelDownload(response);
        }
    
        /**
         *批量上传
         */
        @PostMapping("/v1/addAll")
        public void dxccAddAll(@RequestParam(value = "addFile") MultipartFile addFile) {
            excelService.addAll(addFile);
        }
    }

    Service:

    package com...service;
    
    import com...utils.ExportExcelUtil;
    import com...utils.ImportExcelUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    import javax.servlet.http.HttpServletResponse;
    import java.io.BufferedInputStream;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * @author lifan
     */
    @Slf4j
    @Service
    public class ExcelService {
    
        public void dataModelDownload(HttpServletResponse response) {
    
            List<List<String>> list = new ArrayList<>();
            List<String> headList = new ArrayList<>();
            //标题行
            headList.add("订单类型");
            headList.add("项目名称");
            headList.add("项目代码");
            headList.add("档次名称");
            headList.add("档次代码");
            headList.add("缴费金额");
            headList.add("有效期起");
            headList.add("有效期止");
            String fileName = "XX档次导入表(模板)";
            list.add(headList);
            //示例数据:
            List<String> cList = new ArrayList<>();
            cList.add("示例:XX-000001");
            cList.add("示例:XX-000002");
            cList.add("示例:XX-000003");
            cList.add("示例:XX-000004");
            cList.add("示例:XX-000005");
            cList.add("示例:XX-200");
            cList.add("示例:XX-202101");
            cList.add("示例:XX-202112");
            list.add(cList);
            try {
                ExportExcelUtil.exportExcelModel(response, fileName, list);
            } catch (Exception e) {
                log.error("download error={},fileName={}", e, fileName);
            }
        }
    
        public void addAll(MultipartFile addFile) {
    
            String filename = addFile.getOriginalFilename();
            System.out.println(filename);
    
    //        BufferedInputStream inputStream = (BufferedInputStream) addFile.getInputStream();
            InputStream inputStream = null;
            try {
                inputStream = addFile.getInputStream();
                Map<String, String> map = new HashMap<>();
                //字段转换
                map.put("订单类型", "ddlx");
                map.put("项目名称", "xmmc");
                map.put("项目代码", "xmdm");
                map.put("档次名称", "dcmc");
                map.put("档次代码", "dcdm");
                map.put("缴费金额", "jfje");
                map.put("有效期起", "yxqq");
                map.put("有效期止", "yxqz");
                List<Map<String, Object>> mapList = ImportExcelUtil.parseExcel(inputStream, filename, map);
                for (Map<String, Object> m : mapList) {
                    //时间格式需要整理一下
                    m.put("yxqq",m.get("yxqq").toString().replace(".00", ""));
                    m.put("yxqz",m.get("yxqz").toString().replace(".00", ""));
                    System.out.println(m);
                    //输出 具体数据,去做下面的处理
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }

    导出辅助类 :

    package com...utils;
    
    import lombok.extern.slf4j.Slf4j;
    import org.apache.poi.hssf.usermodel.*;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.util.List;
    
    /**
     * @author lifan
     * excel 导出-辅助类
     */
    @Slf4j
    public class ExportExcelUtil {
    
        @SuppressWarnings("deprecation")
        public static byte[] exportExcelModel(HttpServletResponse response, String fileNameSheet, List<List<String>> dataList) throws Exception {
            // 生成Excel文件
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
            // 创建Sheet
            HSSFSheet sheet = hssfWorkbook.createSheet(fileNameSheet);
            sheet.setDefaultColumnWidth((short) 20);
            String fileName = fileNameSheet;
    
            HSSFRow row ;
            int dataIndex = dataList.get(0).size();
            // 记录额外创建的sheet数量
            int index = 0;
            for (int r = 0; r < dataList.size(); r++) {
                //限制Excel 6w --- Excel导出超过字段限制65535
                if ( r % 60000 == 0 && r != 0 ) {
                    sheet = hssfWorkbook.createSheet();
                    index++;
                }
                row = sheet.createRow(r - (index * 60000));
                for (int j = 0; j < dataIndex; j++) {
                    row.createCell(j,HSSFCell.CELL_TYPE_STRING).setCellValue(dataList.get(r).get(j));
                }
            }
    
            if (response != null) {
                response.reset();
                ServletOutputStream outputStream = response.getOutputStream();
                try {
                    fileName = new String(fileName.getBytes(), "iso-8859-1") + ".xls";
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/vnd.ms-excel;charset=utf-8");
                    // b.Content-Disposition 设置要被下载的文件名
                    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                    hssfWorkbook.write(outputStream);
                    outputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                }
            }else{
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                try {
                    hssfWorkbook.write(bos);
                } finally {
                    bos.close();
                }
                return bos.toByteArray();
            }
            return null;
        }
    
        public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
            BufferedOutputStream bos=null;
            FileOutputStream fos=null;
            File file;
            try{
                File dir=new File(filePath);
                if(!dir.exists() && !dir.isDirectory()){
                    dir.mkdirs();
                }
                file=new File(filePath + fileName);
                fos=new FileOutputStream(file);
                bos=new BufferedOutputStream(fos);
                bos.write(bytes);
            }
            catch(Exception e){
                log.error("getFileByBytes 生成文件error={}",e.getMessage());
            }
            finally{
                try{
                    if(bos != null){
                        bos.close();
                    }
                    if(fos != null){
                        fos.close();
                    }
                }
                catch(Exception e){
                    log.error("getFileByBytes error={}",e.getMessage());
                }
            }
        }
    }

    导入辅助类 :

    package com...utils;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.text.DecimalFormat;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import lombok.extern.slf4j.Slf4j;
    
    /**
     * @author lifan
     * excel 导入-辅助类
     */
    @Slf4j
    public class ImportExcelUtil {
    
        private final static String excel2003L = ".xls"; // 2003- 版本的excel
        private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel
    
        /**
         * 将流中的Excel数据转成List<Map>
         *
         * @param in       输入流
         * @param fileName 文件名(判断Excel版本)
         * @param mapping  字段名称映射
         * @return
         * @throws Exception
         */
        public static List<Map<String, Object>> parseExcel(InputStream in, String fileName, Map<String, String> mapping) throws Exception {
            // 根据文件名来创建Excel工作薄
            // Workbook work = getWorkbook(in, fileName);
            Workbook work = WorkbookFactory.create (in);
            if (null == work) {
                throw new Exception ("创建Excel工作薄为空!");
            }
            Sheet sheet = null;
            Row row = null;
            Cell cell = null;
            // 返回数据
            List<Map<String, Object>> ls = new ArrayList<Map<String, Object>> ();
    
            // 遍历Excel中所有的sheet
            for (int i = 0; i < work.getNumberOfSheets (); i++) {
                sheet = work.getSheetAt (i);
                if (sheet == null)
                    continue;
                // 取第一行标题
                row = sheet.getRow (0);
                String title[] = null;
                if (row != null) {
                    title = new String[row.getLastCellNum ()];
    
                    for (int y = row.getFirstCellNum (); y < row.getLastCellNum (); y++) {
                        cell = row.getCell (y);
                        title[y] = String.valueOf (getCellValue (cell));
                    }
    
                } else
                    continue;
                // 遍历当前sheet中的所有行
                for (int j = 1; j < sheet.getLastRowNum () + 1; j++) {
                    row = sheet.getRow (j);
                    Map<String, Object> m = new HashMap<>();
                    // 遍历所有的列
                    for (int y = row.getFirstCellNum (); y < row.getLastCellNum (); y++) {
                        cell = row.getCell (y);
                        String key = title[y];
                        // log.info(JSON.toJSONString(key));
                        String cellValue = "";
                        if (cell != null) {
                            cellValue = String.valueOf (getCellValue (cell));
                        }
                        m.put (mapping.get (key), cellValue);
                    }
                    ls.add (m);
                }
    
            }
            return ls;
        }
    
        /**
         * 描述:对表格中数值进行格式化
         *
         * @param cell
         * @return
         */
        @SuppressWarnings("deprecation")
        public static Object getCellValue(Cell cell) {
            Object value = null;
            DecimalFormat df = new DecimalFormat ("0"); // 格式化number String字符
            SimpleDateFormat sdf = new SimpleDateFormat ("yyyy/MM/dd"); // 日期格式化
            DecimalFormat df2 = new DecimalFormat ("0.00"); // 格式化数字
            DecimalFormat df4 = new DecimalFormat ("0.0000"); // 格式化数字
            switch (cell.getCellType ()) {
                case Cell.CELL_TYPE_STRING:
                    value = cell.getRichStringCellValue ().getString ();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if ("General".equals (cell.getCellStyle ().getDataFormatString ())) {
                        value = df2.format (cell.getNumericCellValue ());
                    } else if ("m/d/yy".equals (cell.getCellStyle ().getDataFormatString ())) {
                        value = sdf.format (cell.getDateCellValue ());
                    } else if ("0.00%".equals (cell.getCellStyle ().getDataFormatString ())) {
                        value = df4.format (cell.getNumericCellValue ());
                    } else if ("0%".equals (cell.getCellStyle ().getDataFormatString ())) {
                        value = df4.format (cell.getNumericCellValue ());
                    } else {
                        value = df2.format (cell.getNumericCellValue ());
                    }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    value = cell.getBooleanCellValue ();
                    break;
                case Cell.CELL_TYPE_BLANK:
                    value = "";
                    break;
                default:
                    break;
            }
            return value;
        }
    
        /**
         * 描述:根据文件后缀,自适应上传文件的版本
         *
         * @param inStr ,fileName
         * @return
         * @throws Exception
         */
        public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
            Workbook wb = null;
            String fileType = fileName.substring (fileName.lastIndexOf ("."));
            if (excel2003L.equals (fileType)) {
                wb = new HSSFWorkbook (inStr); // 2003-
            } else if (excel2007U.equals (fileType)) {
                wb = new XSSFWorkbook (inStr); // 2007+
            } else {
                throw new Exception ("解析的文件格式有误!");
            }
            return wb;
        }
    
    }

    测试结果:

            导出:

    导入:

     

    package com.lifan.demo.service;

    import com.lifan.demo.utils.ExportExcelUtil;
    import com.lifan.demo.utils.ImportExcelUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    import javax.servlet.http.HttpServletResponse;
    import java.io.BufferedInputStream;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    /**
    * @author lifan
    */
    @Slf4j
    @Service
    public class ExcelService {

    public void dataModelDownload(HttpServletResponse response) {

    List<List<String>> list = new ArrayList<>();
    List<String> headList = new ArrayList<>();
    //标题行
    headList.add("订单类型");
    headList.add("项目名称");
    headList.add("项目代码");
    headList.add("档次名称");
    headList.add("档次代码");
    headList.add("缴费金额");
    headList.add("有效期起");
    headList.add("有效期止");
    String fileName = "XX档次导入表(模板)";
    list.add(headList);
    //示例数据:
    List<String> cList = new ArrayList<>();
    cList.add("示例:XX-000001");
    cList.add("示例:XX-000002");
    cList.add("示例:XX-000003");
    cList.add("示例:XX-000004");
    cList.add("示例:XX-000005");
    cList.add("示例:XX-200");
    cList.add("示例:XX-202101");
    cList.add("示例:XX-202112");
    list.add(cList);
    try {
    ExportExcelUtil.exportExcelModel(response, fileName, list);
    } catch (Exception e) {
    log.error("download error={},fileName={}", e, fileName);
    }
    }

    public void addAll(MultipartFile addFile) {

    String filename = addFile.getOriginalFilename();
    System.out.println(filename);

    // BufferedInputStream inputStream = (BufferedInputStream) addFile.getInputStream();
    InputStream inputStream = null;
    try {
    inputStream = addFile.getInputStream();
    Map<String, String> map = new HashMap<>();
    //字段转换
    map.put("订单类型", "ddlx");
    map.put("项目名称", "xmmc");
    map.put("项目代码", "xmdm");
    map.put("档次名称", "dcmc");
    map.put("档次代码", "dcdm");
    map.put("缴费金额", "jfje");
    map.put("有效期起", "yxqq");
    map.put("有效期止", "yxqz");
    List<Map<String, Object>> mapList = ImportExcelUtil.parseExcel(inputStream, filename, map);
    for (Map<String, Object> m : mapList) {
    //时间格式需要整理一下
    m.put("yxqq",m.get("yxqq").toString().replace(".00", ""));
    m.put("yxqz",m.get("yxqz").toString().replace(".00", ""));
    System.out.println(m);
    //输出 具体数据,去做下面的处理
    }
    } catch (Exception e) {
    e.printStackTrace();
    }

    }
    }
  • 相关阅读:
    【模板】O(nlongn)求LIS
    【图论】用线段树写Dijikstra!!
    【图论】最短路总结
    【codeforces841A】Generous Kefa
    【模板】Tarjian求LCA
    【模板】 RMQ求区间最值
    【模板】map入门
    【二分 贪心】覆盖问题 BZOJ1052 HAOI2007
    【dp】10-15题解 snake vs block
    【模拟】10-15 题解 trans
  • 原文地址:https://www.cnblogs.com/lifan12589/p/15337828.html
Copyright © 2020-2023  润新知