概要
springboot实现文件下载和导入
例如:
- 下载导入模板,上传文件进行导入
文件下载
方式一:下载服务器上的文件模板
下面展示一些 文件下载工具类
。
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
public class FileUtils {
public static void download(HttpServletResponse response, String filePath, String fileName){
try {
//通用的mime类型
response.setContentType("application/octet-stream");
//会出现文件名乱码问题
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
//以下设置请求头能解决下载的文件名乱码问题
response.setHeader("Content-Disposition", "attachment;filename=;filename*=utf-8''"+URLEncoder.encode(fileName,"UTF-8"));
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
writeBytes(is, response.getOutputStream());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void writeBytes(InputStream is, OutputStream os) {
try {
byte[] buf = new byte[1024];
int len = 0;
while((len = is.read(buf))!=-1)
{
os.write(buf,0,len);
}
}catch (Exception e) {
throw new RuntimeException(e);
}finally {
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
controller接口层
@ApiOperation("下载通讯录模板")
@GetMapping("download_template")
public Result download(HttpServletResponse httpServletResponse) {
String fileName = "通讯录导入模板.xlsx";
String filePath = "template/" + fileName;
FileUtils.download(httpServletResponse,filePath,fileName);
return Result.success();
}
提示:要下载的文件要放在resource下,可创建自定义文件夹
方式二:通过代码创建excel响应给页面
例如:
- 通过代码创建excel文件,通过流的方式响应给页面
// 创建一个新的工作簿和工作表
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Data");
sheet.setDefaultColumnWidth(12);
// 创建流量卡厂商选项列表
TrafficCardManufacturerEnum[] manufacturers = TrafficCardManufacturerEnum.values();
List<String> manufacturerOptions = new ArrayList<>();
for (TrafficCardManufacturerEnum manufacturer : manufacturers) {
manufacturerOptions.add(manufacturer.getLabel()); // 添加枚举值的名称到选项列表
}
// 创建下拉框单元格样式
DataValidationHelper validationHelper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(manufacturerOptions.toArray(new String[0]));
CellRangeAddressList addressList = new CellRangeAddressList(1, 1000, 3, 3); // 假设有1000行数据,"性别"列是第二列(索引为1)
DataValidation validation = validationHelper.createValidation(constraint, addressList);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
// 创建表头行
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("设备ID");
// 创建设备名称单元格,并设置文字为红色
Cell deviceNameCell = headerRow.createCell(1);
deviceNameCell.setCellValue("设备名称");
// 创建字体,并设置为红色
Font font = workbook.createFont();
font.setColor(HSSFColor.HSSFColorPredefined.RED.getIndex()); // 字体颜色为红色
// 创建样式,并将字体应用于样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
deviceNameCell.setCellStyle(cellStyle);
headerRow.createCell(2).setCellValue("相机号");
headerRow.createCell(3).setCellValue("流量卡厂商");
headerRow.createCell(4).setCellValue("流量卡号");
headerRow.createCell(5).setCellValue("username");
headerRow.createCell(6).setCellValue("password");
headerRow.createCell(7).setCellValue("dtu");
headerRow.createCell(8).setCellValue("主板号");
Cell notes = headerRow.createCell(9);
notes.setCellValue("注:标记红色为必填,流量卡和流量卡厂商必须同时存在,设备ID不填时会自动生成,一次最多导入1000条");
notes.setCellStyle(cellStyle);
// 将工作簿写入ByteArrayOutputStream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
workbook.close();
// 设置HTTP响应头
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template.xlsx");
// 将Excel文件写入响应输出流
ServletOutputStream outStream = response.getOutputStream();
outStream.write(outputStream.toByteArray());
outStream.flush();