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

数据库表数据导出为Excel

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

数据库表数据导出为Excel

话不多说,火速需求实现。

      引入maven坐标依赖

        
              com.alibaba
              easyexcel
               2.1.1
        

        构建导出表字段所对应的实体对象。

public class AdminExcelProperty {
    @ExcelProperty(value = "用户id",index = 0)
    private Long id;
    @ExcelProperty(value = "用户名",index = 1)
    private String username;
    @ExcelProperty(value = "密码",index = 2)
    private String password;
    @ExcelProperty(value = "头像",index = 3)
    private String icon;
    @ExcelProperty(value = "邮箱",index = 4)
    private String email;

            对应mapper

public interface AdminMapper extends BaseMapper {

}

        对应mapper.xml 





    
    
        
        
        
        
        
     

        对应service

public interface ExportService {
   void exportExcel(HttpServletResponse response);
}

        对应serviceimpl

@Service
public class ExportServiceImpl implements ExportService {
    //查询表中的数据
    @Autowired
    private  AdminMapper adminMapper;
    @Override
    public void exportExcel(HttpServletResponse response) {
        List list = adminMapper.selectList(null);
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 名字根据个人需求可以动态传入
            String fileName = URLEncoder.encode("ums_admin", "UTF-8").replaceAll("\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AdminExcelProperty.class).sheet("admin").doWrite(list);
        } catch (
                IOException e) {
            e.printStackTrace();
        }
    }
}

     对应controller

@RestController
@RequestMapping(value =  "/export")
public class ExportDBController {
    @Autowired
    private ExportService exportService;

    @GetMapping(value = "/admin")
    public void exportAdminExcel(HttpServletRequest httpServletRequest, HttpServletResponse response){
        exportService.exportExcel(response);
    }
}

       直接调用接口实现,其中可以根据自己不同需求做相应的修改

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

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

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