超级简单的上传Excel流文件至——七牛云服务器:
文章目录
问题描述
例如:数据在导出时,大量数据存储导出需要消耗大量时间,可以通过任务队列模式,然后将导出文件上传到七牛云服务器进行下载。
首先需要保证pom依赖加载正确:
<!-- 导出Excel相关的包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.7</version>
</dependency>
<!-- hutool 工具 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
</dependency>
<!-- 七牛的SDK -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
</dependency>
一、编写上传的服务(首先是一个实例代码)
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.*;
public class ExcelToQiniu {
// 设置七牛云账户的Access Key和Secret Key
private static final String ACCESS_KEY = "your-access-key";
private static final String SECRET_KEY = "your-secret-key";
// 设置七牛云存储空间名和上传文件的Key
private static final String BUCKET_NAME = "your-bucket-name";
private static final String UPLOAD_KEY = "your-upload-key";
// 下载Excel文件的接口URL
private static final String EXCEL_URL = "your-excel-url";
public static void main(String[] args) {
// 创建七牛云上传配置
Configuration cfg = new Configuration(Zone.autoZone());
cfg.useHttps = true;
cfg.connectTimeout = 60 * 1000; // 连接超时时间(单位:毫秒)
cfg.responseTimeout = 60 * 1000; // 响应超时时间(单位:毫秒)
cfg.ioTimeout = 60 * 1000; // 数据传输超时时间(单位:毫秒)
cfg.useHttp2 = true; // 是否使用HTTP2协议,默认为true
cfg.domain = "your-domain"; // 设置七牛云存储域名,这里需要替换为您自己的域名
cfg.baseURL = "https://"; // 设置七牛云存储的Base URL,这里需要替换为您自己的Base URL
cfg.userAgent = "your-user-agent"; // 设置User Agent,这里需要替换为您自己的User Agent
// 创建七牛云上传实例
UploadManager uploadManager = new UploadManager(cfg);
// 创建七牛云授权对象,用于生成上传Token
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
String token = auth.uploadToken(BUCKET_NAME);
// 创建HTTP请求对象,用于获取Excel文件流
HttpClient httpClient = new DefaultHttpClient();
HttpHost httpHost = new HttpHost(EXCEL_URL);
HttpGet httpGet = new HttpGet(EXCEL_URL);
httpGet.addHeader("Authorization", "Bearer " + token); // 添加授权信息
try {
HttpResponse response = httpClient.execute(httpHost, httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
// 获取Excel文件流
InputStream inputStream = response.getEntity().getContent();
// 上传Excel文件到七牛云并获取上传成功后的URL
StringMap params = new StringMap()
.put("name", UPLOAD_KEY) // 设置上传文件的Key,这里使用预设的Key,也可以自定义Key
.put("deleteAfterDays", 7); // 设置文件过期时间,这里设置为7天后过期,也可以根据需要调整过期时间
String uploadUrl = uploadManager.upload(inputStream, "excel", params); // 上传Excel文件,并返回上传成功后的URL
System.out.println("Excel file uploaded to Qiniu Cloud successfully! URL: " + uploadUrl);
} else {
System.out.println("Failed to download Excel file from the API.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭HTTP请求连接和HTTP客户端对象,释放资源
httpClient.getConnectionManager().shutdown();
}
}
}
二、作者编写如下
1.服务层代码
代码如下(示例):
//服务层 QiniuService
String upload(InputStream is, String uploadPath, StringMap params, String fileContextType);
//实现层 QiniuServiceImpl
@Override
public String upload(InputStream is, String uploadPath, StringMap params, String fileContextType) {
UploadManager uploadManager = getUM();//已封装创建过程,可参考上方生成示例代码进行编写
try {
Response response = uploadManager.put(is, uploadPath, qiniuToken(), params, fileContextType);
DefaultPutRet result = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return result.key;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
2.Excel生成代码
excel生成过程如下(示例):
ExcelWriter excelWriterResponse = null;
//得到导出的excel表头
List<List<String>> listHead = getheader(Id);
//创建导出表信息 new LocalDateTimeConverter()时间转换使用
WriteSheet writeSheet = EasyExcel.writerSheet("exportSheetName").registerConverter(new LocalDateTimeConverter()).build();
List<List<String>> exportListAll = new ArrayList<>();
//得到导出数据
List<ExcelDataExportVO> list = "your exportData";
//得到写入excel中的数据 类似于一个数据预处理的操作,将数据整理为导出模型数据
combineExportListData(list);
//上传到七牛云下载
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//使用该流上传,可以得到流的具体内容和长度
excelWriterResponse = EasyExcel.write(byteArrayOutputStream).head(listHead).build();
excelWriterResponse.write(exportListAll, writeSheet);//将数据写入流中
excelWriterResponse.finish();//一定要写,代表流写入完毕,这样才会在流中取到对应的数据
时间转换类代码如下(示例):
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* 自定义LocalDateStringConverter
* 在对应的导出字段上写注解也可
*/
public class LocalDateTimeConverter implements Converter<LocalDateTime> {
@Override
public Class supportJavaTypeKey() {
return LocalDateTime.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
@Override
public CellData convertToExcelData(LocalDateTime localDateTime, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = formatter.format(localDateTime);
return new CellData(format);
}
}
2.上传文件至七牛云服务器
过程如下(示例):
//日期路径
DateFormat df = new SimpleDateFormat("yyyyMMdd");
String month = df.format(new Date());
String uploadPath = "";
//文件类型
InputStream is = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
uploadPath = "temp/" + WxStorageProperties.downloadPrefix + "/" + month;
String uploadFileName = "exportDataFileName" + ".xlsx";
uploadPath = uploadPath + "/" + uploadFileName;
//由于此处导出的是excel文件流,流的最终格式也必须是这样的,至于导出别的可以对应选择
String key = qiniuService.upload(is, uploadPath, null, "application/vnd.ms-excel");
log.info("exportDataTask--->key--->:{}",key);
//回写数据信息
补!!!
对于上述中七牛方法的最后一个参数,fileContextType—————准确来说应该是MIME类型
小编搜集到一些,以供大家学习
以下是一些常见的MIME类型:
text/plain:普通文本,没有特定的subtype。
text/html:HTML文本。
text/css:CSS文本。
text/javascript:JavaScript代码。
text/ecmascript:ECMAScript(JavaScript)代码。
text/x-javascript:扩展的JavaScript代码。
text/json:JSON文本。
text/xml:XML文本。
image/jpeg:JPEG图像文件。
image/png:PNG图像文件。
image/gif:GIF图像文件。
image/bmp:BMP图像文件。
image/svg+xml:SVG(可缩放矢量图形)图像文件。
audio/mpeg:MP3音频文件。
audio/ogg:Ogg Vorbis音频文件。
audio/*:各种音频文件类型,包括WAV、AU、MIDI等。
video/mp4:MP4视频文件。
video/mpeg:MPEG视频文件。
video/quicktime:QuickTime视频文件。
video/x-msvideo:AVI视频文件。
video/*:各种视频文件类型,包括WMV、AVI、MPG等。
application/pdf:PDF文档。
application/json:JSON文本。
application/javascript:JavaScript代码。
application/ecmascript:ECMAScript(JavaScript)代码。
application/octet-stream:二进制数据。
application/*:各种应用程序文件类型,包括文本、图像、音频、视频等。
此次用到的是application/vnd.ms-excel是一种用于创建和读取Microsoft Excel电子表格文件的MIME类型。它使用了Microsoft Office Open XML(OOXML)规范,使得电子表格文件具有较高的兼容性和可读性。这种文件格式支持更大的电子表格,包含更多的新功能,例如更好的图表功能、更丰富的样式和更安全的加密选项,因此相对于旧版的.xls格式,它更加流行和广泛使用。
根据得到的key,然后配上设置的七牛域名就可以访问进行下载啦
总结
例如:以上就是今天要讲的内容,本文仅仅简单介绍了ExcelWriter的使用,而ExcelWriter提供了大量能使我们快速便捷地处理数据的函数和方法,如果想要设计一个漂亮的excel导出页面的话,还需要学习一下对应的设计部分,小编就不在这里进行介绍啦。