1. 程式人生 > >Spring cloud 後臺 download(下載) Excel, 查詢資料上傳到微軟 Azure 返回下載連結

Spring cloud 後臺 download(下載) Excel, 查詢資料上傳到微軟 Azure 返回下載連結

1.所需 jar 包:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

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<UserFeedback> userFeedbackList = userFeedbackService.selectByDropDown(param);         //自己封裝的 Bo 每個人寫的物件不一樣 List<UserFeedbackDownloadBo> 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; } }