栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot文件上传与下载 以及页面内容的导出

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot文件上传与下载 以及页面内容的导出

需要用到的jar包依赖主要如下



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.5
         
    
    com.llf
    up_and_down
    0.0.1-SNAPSHOT
    up_and_down
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.apache.poi
            poi
            3.17
        
        
        
            org.apache.poi
            poi-ooxml
            3.17
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.3
        
        
        
            mysql
            mysql-connector-java
            8.0.26
        
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



准备工作

1.创建一张数据库表 作为数据存储的工具

CREATE TABLE `excel` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `role` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

2、创建springboot项目 创建对应实体类 、Mapper、service、controller

@Component
@TableName(value = "excel")
public class Excel  implements Serializable {
	//设置主键策略
    @TableId(type = IdType.AUTO)
    private Integer id;

    private String username;

    private String email;

    private String password;

    private String role;

    public Excel() {
    }

    public Excel(Integer id, String username, String email, String password, String role) {
        this.id = id;
        this.username = username;
        this.email = email;
        this.password = password;
        this.role = role;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "Excel{" +
                "id='" + id + ''' +
                ", username='" + username + ''' +
                ", email='" + email + ''' +
                ", password='" + password + ''' +
                ", role='" + role + ''' +
                '}';
    }

}
下载模块
       //要下载的文件地址
        String  path = "E:\IDEA工作区\up_and_down\src\main\resources\excel";
        String  fileName = "model.xls";

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path,fileName);
        //2、 读取文件--输入流
        InputStream input=new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff =new byte[1024];
        int index=0;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return true;

这里需要注意的只有文件的地址和文件的名字 其他都是死代码

方法写完之后 在前端页面进行点击事件访问即可




    
    Title


文件
下载模板 查看全部信息

上传数据到数据库

首先在service层进行具体的业务代码编写

@Service
public class ExcelServiceImpl extends ServiceImpl implements ExcelService{

    @Autowired
    private ExcelMapper excelMapper;
    @Override
    public boolean getExcel(MultipartFile file) throws Exception {

        List list = new ArrayList();

//1.得到上传的表
        Workbook workbook2 = WorkbookFactory.create(file.getInputStream());
//2、获取test工作表
        Sheet sheet2 = workbook2.getSheet("test");
//获取表的总行数
        int num = sheet2.getLastRowNum();
//System.out.println(num);
//总列数
        int col = sheet2.getRow(0).getLastCellNum();
//遍历excel每一行  从1开始 上传内容 不上传表格的表头部分
        for (int j = 1; j <= num; j++) {
            Row row1 = sheet2.getRow(j);
//如果单元格中有数字或者其他格式的数据,则调用setCellType()转换为string类型  为了保险  全部转换为string类型
            Cell cell1 = row1.getCell(0);
            cell1.setCellType(CellType.STRING);
//获取表中第i行,第2列的单元格
            Cell cell2 = row1.getCell(1);
            cell2.setCellType(CellType.STRING);
//excel表的第i行,第3列的单元格
            Cell cell3 = row1.getCell(2);
            cell3.setCellType(CellType.STRING);
//excel表的第i行,第4列的单元格  依次类推
            Cell cell4 = row1.getCell(3);
            cell4.setCellType(CellType.STRING);
//这里new 一个对象,用来装填从页面上传的Excel数据,字段根据上传的excel决定
            Excel excel= new Excel();
            excel.setUsername(cell1.getStringCellValue());
            excel.setEmail(cell2.getStringCellValue());
            excel.setPassword(cell3.getStringCellValue());
            excel.setRole(cell4.getStringCellValue());

            list.add(excel);

        }
        list.forEach(x->{
            excelMapper.insert(x);
        });


        return true;
    }


}

cell的实例化对象的数量取决于模板中字段的数量,可以自由增加或减少
在调用Execl对象赋值时 注意字段与字段之间的相等

紧接着在controller中进行service层的调用

    @PostMapping("/excel")
    public String upload(MultipartFile file, HttpSession session) throws Exception {
    //file是前端页面的文件参数  方法是自己定义的方法 
        boolean flag = excelService.getExcel(file);
        if(flag){
        session.setAttribute("message","上传成功");
            return "redirect:/";
        }else{
            session.setAttribute("message","上传成功");
            return "upload";

        }

    }

页面内容导出



    
    Title



id 姓名 邮箱 密码 角色

依然是用到table2excel.js 来实现页面数据的导出

使用到了一个获取所有信息的接口

 @GetMapping("/getAll")
    public String getall(Model model){
        List list = excelMapper.selectList(null);
        model.addAttribute("list",list);
        return "all";
    }

用到的insert和selectlist 两个方法 都是mybatis-plus自带的 不需要自己编写
也可以在上传文件的时候通过修改具体的cell遍历代码和excel赋值代码 达到自己想要的效果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/603354.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号