问题还原:
在做项目时,很多时候会用到上传、下载Excel文件。此处,笔者需要实现Excel文件下载功能。具体实现如下所述。
解决方案:
Vue端相关代码如下:
定义按钮:
<el-button
type="primary"
icon="el-icon-upload2"
@click="downloadExcel()"
>
下载Excel
</el-button>
JS方法:
methods: {
downloadExcel () {
// 下载好用版
Vue.axios({
method: 'get',
url: '/***/downloadExcel',
responseType: 'arraybuffer'
}).then((response) => {
console.log('response====================')
console.log(response)
const link = document.createElement('a')
link.style.display = 'none'
const url = window.URL.createObjectURL(new Blob([response], { type: 'application/vnd.ms-excel' }))
link.href = url
link.setAttribute('download', '***.xlsx')
document.body.appendChild(link)
link.click()
}).catch((error) => {
this.$message.error(error)
})
}
}
SpringBoot/SpringCloud端相关代码如下:
Controller层代码:
@GetMapping("/downloadExcel")
@ApiOperation(value = "下载Excel")
public void getExcelData(HttpServletResponse response) throws IOException {
ExcelUtil.readExcelToIO ("D:\\\\ExcelTest\\\\**.xlsx", response);
}
ExcelUtil代码如下:
public static void readExcelToIO(String fileName, HttpServletResponse response) throws IOException {
//判断是否为excel类型文件
if(!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
{
throw new RuntimeException("所传入文件不是Excel文件!");
}
//读取Excel文件
File excelFile = new File(fileName.trim());
InputStream inputStream = new FileInputStream(excelFile);
// 构造 XSSFWorkbook 对象,strPath 传入文件路径
Workbook workbook = null;
//获取Excel工作薄
if (excelFile.getName().endsWith("xlsx")) {
workbook = new XSSFWorkbook(inputStream);
} else {
workbook = new HSSFWorkbook(inputStream);
}
if (workbook == null) {
throw new RuntimeException("Excel文件有问题,请检查!");
}
// 读取第一个sheet页表格内容
Sheet sheet = workbook.getSheetAt(0);
OutputStream os = response.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
// 返回数据到输出流对象中
os.write(baos.toByteArray());
os.flush();
os.close();
}
PS:欢迎大家点赞、关注、支持。如有需要,欢迎添加博主QQ沟通交流!QQ:156587607