导出xml格式数据
文章目录
- 导出xml格式数据
- 前言
- 一、实现代码
- 1.controller层
- 2.接口层
- 3.接口实现类
- 4.XmlUtil 工具类
- 二、文件导出效果
- 总结
前言
springBoot项目实现在线导出xml格式文件数据的功能。
一、实现代码
1.controller层
@GetMapping("/record/_export")
@ApiOperation("查询记录导出")
public void recordExport(HttpServletResponse response, RecordSearchRequest query) throws IOException {
ruleVerifyResultService.recordExport(response, query);
}
RecordSearchRequest为请求查询条件,根据条件导出对应的记录。
2.接口层
public interface ResultService extends IService<RuleVerifyResultEntity> {
/**
* 记录导出
* @param query
* @return
*/
void recordExport(HttpServletResponse response, RecordSearchRequest query) throws IOException;
}
3.接口实现类
@Override
public void queryRecordExport(HttpServletResponse response, RuleVerifyRecordSearchRequest query) throws IOException {
LocalDateTime startExecuteTime = null;
LocalDateTime endExecuteTime = null;
//设置导出文件名称
String fileName = "检验记录列表数据";
if (ObjectUtils.isNotEmpty(query.getExecuteStartTime())) {
startExecuteTime = query.getExecuteStartTime().atStartOfDay();
endExecuteTime = query.getExecuteStartTime().atTime(23, 59, 59);
}
//查询需要导出的数据,用list集合接收
List<RuleVerifyRecordEntity> recordList = ruleVerifyRecordMapper.selectList(Wrappers.<RuleVerifyRecordEntity>lambdaQuery().
// 关键字搜索
and(StringUtils.isNotEmpty(query.getKeywords()), wrapper ->
wrapper.like(RuleVerifyRecordEntity::getTableName, query.getKeywords()).
or().like(RuleVerifyRecordEntity::getTableRemark, query.getKeywords()).
or().like(RuleVerifyRecordEntity::getDatasourceName, query.getKeywords())
)
orderByDesc(RuleVerifyRecordEntity::getExecuteStartTime)
);
//3.导出xml数据
if (ObjectUtils.equals(ExportTypeEnum.XML.getValue(), query.getExportType())) {
//给浏览器设置响应头:Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xml", "UTF-8"));
//给浏览器设置响应头:文件类型
response.setContentType("application/octet-stream;charset=utf-8");
try {
XmlUtil.downloadXml(recordList, (element, row) -> {
element.addElement("tableName").addAttribute("comment", "表名称").setText(row.getTableName());
element.addElement("ruleStrengthOrWeekCount").addAttribute("comment", "异常").setText(StringUtils.join(row.getRuleStrengthCount(), "/", row.getRuleWeekCount()));
element.addElement("executeStatus").addAttribute("comment", "执行状态").setText(ObjectUtils.isNotEmpty(row.getExecuteStatus()) ? row.getExecuteStatus().toString() : null);
element.addElement("schedulerInfo").addAttribute("comment", "调度信息").setText(row.getSchedulerInfo());
element.addElement("executeStartTime").addAttribute("comment", "开始时间").setText(DateTimeUtil.toDateTimeStr(ObjectUtils.isNotEmpty(row.getExecuteStatus()) ? row.getExecuteStartTime() : LocalDateTime.now()));
element.addElement("executeEndTime").addAttribute("comment", "结束时间").setText(DateTimeUtil.toDateTimeStr(ObjectUtils.isNotEmpty(row.getExecuteEndTime()) ? row.getExecuteEndTime() : LocalDateTime.now()));
}, response);
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
throw new RuntimeException(e);
}
}
else {
throw new BizException("不支持的文件导出类型");
}
}
4.XmlUtil 工具类
import java.io.*;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.function.BiConsumer;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import javax.servlet.http.HttpServletResponse;
/**
* @author Benson
*/
@Slf4j
public class XmlUtil {
public static <T> boolean downloadXml(List<T> list, BiConsumer<Element, T> appendFunc, HttpServletResponse response) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("Rows");
try {
for (int i = 0; i < list.size(); i++) {
Element topElement = root.addElement("Row");
T rowData = list.get(i);
appendFunc.accept(topElement, rowData);
}
} catch (Exception e) {
e.printStackTrace();
}
downloadXmlStream(document, response);
return true;
}
private static boolean downloadXmlStream(Document document, HttpServletResponse response) {
try {
response.setContentType("text/xml;charset=utf-8");
response.setHeader("cache-control", "no-cache");
XMLWriter w = new XMLWriter(response.getWriter());
w.write(document);
w.close();
return true;
} catch (Exception e) {
e.printStackTrace();
log.error("下载xml文件失败,错误信息", e);
throw new RuntimeException("生成xml文件失败");
}
}
}
二、文件导出效果
总结
本次实现了xml文件的导出功能,欢迎交流学习。