Java 导出为Excel && 根据链接下载图片并打包

这两个功能都是很常见的,有工具类可以直接用,你要做的,只是传入数据而已

1. 导出为Excel

1.引入 poi 依赖
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>
2. 引入工具类 ExcelUtil
package com.gxx.nonmotorvehicle.util;

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.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExcelUtil {

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * @param response
     * @param fileName excel文件名
     * @param headMap  表头map
     * @param dataList 表格数据
     */
    public static void exportXlsx(HttpServletResponse response, String fileName, Map<String, String> headMap, List<Map<String, Object>> dataList) {
        Workbook workbook = exportXlsx(fileName, headMap, dataList);
        exportXlsx(response,fileName,workbook);
    }

    /**
     * @param response
     * @param fileName excel文件名
     */
    public static void exportXlsx(HttpServletResponse response, String fileName, Workbook workbook) {
        response.setContentType("application/binary;charset=ISO8859_1");
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            String fn = new String(fileName.getBytes(), "ISO8859_1");
            response.setHeader("Content-disposition", "attachment; filename=" + fn + ".xlsx");
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 导出数据
     *
     * @param headMap
     * @param dataList
     */
    public static Workbook exportXlsx(String sheetName, Map<String, String> headMap, List<Map<String, Object>> dataList) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(sheetName);

        int rowIndex = 0, columnIndex = 0;
        Set<String> keys = headMap.keySet();

        //表头
        Row row = sheet.createRow(rowIndex++);
        for (String key : keys) {
            Cell cell = row.createCell(columnIndex++);
            cell.setCellValue(headMap.get(key));
        }

        //内容
        if (dataList != null && !dataList.isEmpty()) {
            for (Map<String, Object> map : dataList) {
                row = sheet.createRow(rowIndex++);
                columnIndex = 0;
                for (String key : keys) {
                    Cell cell = row.createCell(columnIndex++);
                    setCellValue(cell, map.get(key));
                }
            }
        }
        return workbook;
    }

    private static void setCellValue(Cell cell, Object obj) {
        if (obj == null) {
            return;
        }
        if (obj instanceof String) {
            cell.setCellValue((String) obj);
        } else if (obj instanceof Date) {
            Date date = (Date) obj;
            if (date != null) {
                cell.setCellValue(format.format(date));
            }
        } else if (obj instanceof Calendar) {
            Calendar calendar = (Calendar) obj;
            if (calendar != null) {
                cell.setCellValue(format.format(calendar.getTime()));
            }
        } else if (obj instanceof Timestamp) {
            Timestamp timestamp = (Timestamp) obj;
            if (timestamp != null) {
                cell.setCellValue(format.format(new Date(timestamp.getTime())));
            }
        } else if (obj instanceof Double) {
            cell.setCellValue((Double) obj);
        } else {
            cell.setCellValue(obj.toString());
        }
    }

}

3. 在 service 层定义列名,以及数据
@Override
    public void exportRoadInfo(HttpServletResponse response) {
    	//1.获取数据
        List<Map<String,Object>> datas = this.list(); 
        
        //2.定义列名 
        Map<String,String> headerMap = new LinkedHashMap<>();   
        headerMap.put("crossing_name","路口");
        headerMap.put("count","违法数量");
        
        //3.调用工具类
        ExcelUtil.exportXlsx(response, "路口违法信息"+new SimpleDateFormat("yyyyMMdd").format(new Date()), headerMap, datas);   
    }

2. 根据链接下载图片并打包

public void downloadPicture(HttpServletResponse response) throws ParseException {
		//1.获取 url 集合
        List<Map<String,Object>> datas = this.list(areaCode, violationType, startTime, endTime);
        List<String> imageUrls = new ArrayList<>();
        int i = 1;
        for(Map mp : datas) {
            if(i > 5000)   break;
            imageUrls.add(mp.get("img_path"));
            i++;
        }
        
        //2.定义包名
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String zipName = dateTime.format(format) + ".zip";
        
        //3.设置请求头
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + zipName);
        response.setCharacterEncoding("utf-8");
        
        //4.下载图片
        ZipOutputStream zipOut = null;
        try {
            zipOut = new ZipOutputStream(response.getOutputStream());
            for (String imageUrl : imageUrls) {
            	//4.1 设置图片名称
                String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
                zipOut.putNextEntry(new ZipEntry(fileName));
                
				//4.2 请求下载图片
                URL url = new URL(imageUrl);
                InputStream in = new DataInputStream(url.openStream());

                byte[] buff = new byte[1024];
                int len;
                while ((len = in.read(buff)) != -1) {
                    zipOut.write(buff, 0, len);
                }
                zipOut.closeEntry();
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipOut != null) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值