HttpMessageXlsConverter
@RequestBody 默认输出为JSON,通过重写AbstractHttpMessageConverter,实现对AjaxResponse输出为Excel格式。
@Service
public class HttpMessageXlsConverter extends AbstractHttpMessageConverter<AjaxResponse> {
private static final MediaType Excel_Type = MediaType.valueOf("application/vnd.ms-excel");
HttpMessageXlsConverter(){
super(Excel_Type);
}
@Override
protected boolean supports(Class<?> clazz) {
return (AjaxResponse.class == clazz);
}
//反序列化
@Override
protected AjaxResponse readInternal(Class<? extends AjaxResponse> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
return null;
}
// for AjaxResponse to serialize
@Override
protected void writeInternal(AjaxResponse t, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
final Workbook workbook = new HSSFWorkbook();
final Sheet sheet = workbook.createSheet();
final Row row = sheet.createRow(0);
row.createCell(0).setCellValue(t.getCode());
row.createCell(1).setCellValue(t.getMessage());
row.createCell(2).setCellValue(t.getData().toString());
workbook.write(outputMessage.getBody());
}
}
POM.xml引入Excel API
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
该文章介绍了一种方法,通过扩展Spring的AbstractHttpMessageConverter,将AjaxResponse的响应转换为Excel格式。具体实现包括重写支持的类检查及读写内部方法,使用ApachePOI库来创建和写入Excel工作簿。
501

被折叠的 条评论
为什么被折叠?



