背景
因临时介入一个项目,需要对excel的上传、下载进行操作。而上传接口是其他人所为,已经将文件直接转换为二进制base64字符串保存到数据库中的clob类型字段中了,所以只能顺着已有的方案进行改造。
导入包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
poi 用于操作excel文件
spring-test 用于MockMultipartFile文件操作
具体实现
3.1 保存
org.springframework.web.multipart.MultipartFile
MultipartFile file;
new String(Base64.encodeBase64(file.getBytes()));
file:入参
3.2 获取
前提:保存的地方,需要定义一个返回类型为String的接口,将已存的clob类型字符串作为出参返回
/** 打印模板地址 */
private static String printTplUrl;
@Value("${print.tpl.url}")
public void setPrintTplUrl(String printTplUrl) {
ExportTableUtils.printTplUrl = printTplUrl;
}
/** 打印模板临时文件地址 */
private static String printTplTempfileUrl;
@Value("${print.tpl.tempfile.url}")
public void setPrintTplTempfileUrl(String printTplTempfileUrl) {
ExportTableUtils.printTplTempfileUrl = printTplTempfileUrl;
}
// 以下代码复制到具体业务代码方法中 //
// 文件全名称
String fileFullName = fileName + ".xlsx";
// 获取模板
String tplString = HttpRequestUtil.CallGet(printTplUrl, request, "utf-8");
// 解码
InputStream inputStream = new ByteArrayInputStream(Base64.decodeBase64(tplString));
MultipartFile file = null;
SXSSFWorkbook wbook = null;
try {
file = new MockMultipartFile(fileFullName, fileFullName, ContentType.APPLICATION_OCTET_STREAM.toString(),
inputStream);
String tempFileUrl = printTplTempfileUrl + fileName + System.currentTimeMillis() + ".xlsx";
File file1 = new File(tempFileUrl);
FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
XSSFWorkbook workbook = new XSSFWorkbook(file1);
// 转为更高版本
wbook = new SXSSFWorkbook(workbook);
} catch (IOException e) {
logger.error(e.getMessage(), e);
} catch (InvalidFormatException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (wbook != null) {
wbook.close();
}
if (stream != null) {
stream.close();
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
代码中操作excel的类有两个(共三个版本),具体有什么异同,请自行百度了解三个版本的差异