Hutool Excel模板下载,Excel数据导入

  • excel导入的时候没有指定表头的head,如果有人修改了excel的head,不影响功能使用

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.8</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.1</version>
        </dependency>
						<-- 添加插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <nonFilteredFileExtensions>
                                    <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
                                    <nonFilteredFileExtension>xls</nonFilteredFileExtension>
                   </nonFilteredFileExtensions>
                </configuration>
            </plugin>

excel 在这里插入图片描述
在这里插入图片描述

package com.example.demo.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("/excel")
public class ExcelController {


  
    @PostMapping("/download")
    public void download(HttpServletResponse response) {
        try {
            // 1 读取对象
            File file = ResourceUtils.getFile("classpath:excel/用户信息.xls");
            InputStream inputStream = new FileInputStream(file);
            final ExcelReader reader = ExcelUtil.getReader(inputStream);
            List<List<Object>> lists = reader.read();
            ExcelWriter writer = ExcelUtil.getWriter(false);
            writer.write(lists);
            //设置列宽
            writer.setColumnWidth(3, 15);
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("settlementFeedback.xls", "UTF-8"));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");


        //设置响应头
       //     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
 //        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
//        response.setContentType("application/vnd.ms-excel");
//        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("fileName"+"_"+sdf.format(new Date()), "UTF-8")+".xlsx");

  
          ServletOutputStream outputStream = response.getOutputStream();
            writer.flush(outputStream, true);
            writer.close();
            IoUtil.close(outputStream);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }


    @PostMapping("/upload")
    public String upload(@RequestParam("uploadFile") MultipartFile multipartFile) {
        String suffex = multipartFile.getOriginalFilename().split("\\.")[1];
        if (!"xls".equals(suffex)) {
            return "导入失败,只支持xls文件上传";
        }
        if (Objects.isNull(multipartFile)) {
            return "导入失败,上传文件为空";
        }
        //得到文件流
        InputStream is = null;
        StringBuffer errMsg = new StringBuffer("");
        try {
            is = multipartFile.getResource().getInputStream();
            //导入的excel 只有五列数据,故此处传5
            List<Map<Integer, String>> importData = getImportData(is, 5);
            for (int i = 0; i < importData.size(); i++) {
                Map<Integer, String> map = importData.get(i);
                try {
                    User user = new User();
                    if (StringUtils.isEmpty(map.get(0))) {
                        continue;
                    }
                    //数字编号和excel列一一对应,如果新增列需要同步改动
                    user.setName(map.get(0));
                    user.setAge(Integer.valueOf(map.get(1)));
                    user.setAddress(map.get(2));
                    user.setEmail(map.get(3));
                    user.setPhone(map.get(4));
                    System.out.println(JSONObject.toJSONString(user));
                } catch (Exception e) {
                  //  log.error("清单反馈上传{}行数据异常->{}",i,e.getMessage());
                    errMsg.append(i+1 + ",");
                }
            }
        } catch (Exception e) {
         //   log.error("医保反馈上传失败->{}",e.getMessage());
            IoUtil.close(is);
        }
        if (errMsg.length() > 0) {
            return errMsg.toString() + "行数据导入失败,其余导入成功.";
        }
        return "导入成功";
    }

    /**
     *
     * @param is
     * @param size excel 列的个数
     * @return
     */
    public static List<Map<Integer, String>> getImportData(InputStream is,int size) {
        if (is == null) {
            return Collections.emptyList();
        }
        Workbook workbook = null;
        try {
            workbook = Workbook.getWorkbook(is);
        } catch (BiffException | IOException e) {
            //log.error(e.getMessage(), e);
            return Collections.EMPTY_LIST;
        }
        if (workbook == null) {
            return Collections.emptyList();
        }
        //第一个sheet
        Sheet sheet = workbook.getSheet(0);
        //行数
        int rowCounts = sheet.getRows() - 1;
        if (rowCounts == 0) {
            return Collections.emptyList();
        }
        List<Map<Integer, String>> list = new ArrayList<>(Math.max(rowCounts, 0));
        //双重for循环取出数据
        for (int i = 1; i <= rowCounts; i++) {
            Map<Integer, String> params = new HashMap<>();
            //获取第i行数据
            Cell[] cells = sheet.getRow(i);
            //判断是否是空行
            boolean empty = Arrays.stream(cells).allMatch(cell -> CellType.EMPTY.equals(cell.getType()));
            if (!empty) {
                for (int j = 0; j < size; j++) {
                    //获取低i行第J列数据
                    Cell cell = sheet.getCell(j, i);
                    params.put(j, cell.getContents());
                }
                list.add(params);
            } else {
                break;
            }
        }
        return list;
    }
}

代码有点 遗憾就是导出 名字不能是中文 如果解决了 会继续补充

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值