Spring cloud 后台 download(下载) Excel, 查询数据上传到微软 Azure 返回下载链接

1.所需 jar 包:


    org.apache.poi
    poi
    3.17

2. 代码:

package com.dmap.ucenter.service.background.impl;

import com.dmap.base.units.azure.blob.AzureApp;
import com.dmap.ucenter.bo.background.UserFeedbackDownloadBo;
import com.dmap.ucenter.constants.UCenterConstant;
import com.dmap.ucenter.controller.background.param.SelectDropDownParam;
import com.dmap.ucenter.po.UserFeedback;
import com.dmap.ucenter.service.background.UserFeedbackDownloadService;
import com.dmap.ucenter.service.background.UserFeedbackService;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.CloudBlockBlob;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserFeedbackDownloadServiceImpl implements UserFeedbackDownloadService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserFeedbackService userFeedbackService; //这是自己写的查询数据库的接口

    @Override
    public String userFeedbackDownloadByDropDown(SelectDropDownParam param) {//传过来的查表参数
        String returnValue = null;
        if (param == null) {
            return returnValue;
        } // 注意: 这里的 Excel 列名和数据表一致对应
        String[] headers = {"id", "用户id", "问题描述", "联系方式", "电话版本", "dmap版本", "手表版本", "固件版本",
                "图片地址1", "图片地址2", "图片地址3", "图片地址4", "问题提交时间", "记录创建时间", "异常类型"};//导出的Excel头部
          //查表获得数据,这个可以自己写
          List userFeedbackList = userFeedbackService.selectByDropDown(param);
        //自己封装的 Bo 每个人写的对象不一样
        List userFeedbackDownloadBoList = new ArrayList<>();
        userFeedbackList.forEach(uUserFeedback ->
                userFeedbackDownloadBoList.add(new UserFeedbackDownloadBo(uUserFeedback))
        );
        // 声明一个工作薄
          HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
          HSSFSheet sheet = workbook.createSheet();
        // 设置表格默认列宽度
          sheet.setDefaultColumnWidth((short) 20);
        HSSFRow row = sheet.createRow(0);
        row.setHeight((short) 400); //设置行高
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);// for 循环写入 Excel 表格第一行的上面定义的 headers 列名
        }
        //遍历集合数据,产生数据行
          Iterator iterator = userFeedbackDownloadBoList.iterator();
        int rowIndex = 0;
        while (iterator.hasNext()) {
            rowIndex++;
            row = sheet.createRow(rowIndex);
            row.setHeight((short) 300);
            UserFeedbackDownloadBo userFeedbackDownloadBo = (UserFeedbackDownloadBo) iterator.next();
            //利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
               Field[] fields = userFeedbackDownloadBo.getClass().getDeclaredFields();
            for (short i = 0; i < fields.length; i++) {
                HSSFCell cell = row.createCell(i);
                Field field = fields[i];
                String fieldName = field.getName();
                String getMethodName = "get"
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    Class feedbackVoClass = userFeedbackDownloadBo.getClass();
                    Method getMethod = feedbackVoClass.getMethod(getMethodName, new Class[]{});
                    Object value = getMethod.invoke(userFeedbackDownloadBo, new Object[]{});
                    String textValue = (value == null) ? "" : value.toString();

                    HSSFRichTextString richString = new HSSFRichTextString(textValue);
                    HSSFFont hssfFont = workbook.createFont();
                    hssfFont.setColor(HSSFColor.BLACK.index);//定义Excel数据颜色
                        richString.applyFont(hssfFont);
                    cell.setCellValue(richString);
                } catch (SecurityException | NoSuchMethodException | IllegalArgumentException
                        | IllegalAccessException | InvocationTargetException e) {
                    logger.error("app用户反馈download Excel: ", e);
                }
            }
        }

        //拼装blobName
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateTime = dateFormat.format(new Date());
        String fileName = UCenterConstant.USER_FEEDBACK_DOWNLOAD_FILE_NAME + System.currentTimeMillis() + ".xlsx";
        String blobName = dateTime + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "/" + fileName;

        String accountName = UCenterConstant.ACCOUNT_NAME;
        String accountKey = UCenterConstant.ACCOUNT_KEY;
        String containerName = UCenterConstant.CONTAINER_NAME;

        //获取或创建container 这里参考另外一片文章
        CloudBlobContainer blobContainer = AzureApp.getCloudBlobContainer(accountName, accountKey, containerName);
        //设置文件类型,并且上传到azure blob
        try {
            CloudBlockBlob blob = blobContainer.getBlockBlobReference(blobName);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            byte[] bytes = outputStream.toByteArray();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

            blob.upload(inputStream, bytes.length);
            returnValue = blob.getUri().toString(); // 返回 文件下载 url
        } catch (URISyntaxException | StorageException | IOException e) {
            logger.error("app用户反馈download Excel: ", e);
        }

        return returnValue;
    }

}

你可能感兴趣的:(程序人生,java)