自我总结:结构可能比较复杂,不过涵盖知识点多
PDF导出
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@RestController
public class InspectRecordPdfController extends BaseController {
@Autowired
InspectRecordService inspectRecordService;
@RequestMapping(value = "/url/pdf/{id}", method = {RequestMethod.GET})
@ResponseBody
public void pdfExport(@PathVariable("id") Long id, HttpServletResponse response) {
RespDto<InspectRecord> respDto = inspectRecordService.get(id);
if (respDto.getSuccess()) {
InspectRecord record = respDto.getData();
try {
covertPdf(record, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void covertPdf(InspectRecord record, HttpServletResponse response) throws IOException, DocumentException {
// 第一步,实例化一个document对象
Document document = new Document();
String filename = record.getName() + ".pdf";
// 清空response,否则可能会对程序有影响,因为在此之前有可能也用到了response,若不reset,后面的setCntentoType()有可能失效
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
// 第二步,设置要到出的路径
// 如果是浏览器通过request请求需要在浏览器中输出则使用下面方式
OutputStream out = response.getOutputStream();
// 第三步,设置字符,宋体
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontZH = new Font(bfChinese, 12.0F, Font.NORMAL);
// 第四步,将pdf文件输出到磁盘
PdfWriter.getInstance(document, out);
// 第五步,打开生成的pdf文件
document.open();
Font greenFont = new Font(bfChinese);
greenFont.setColor(BaseColor.GREEN);
Font redFont = new Font(bfChinese);
redFont.setColor(BaseColor.RED);
Font orangeFont = new Font(bfChinese);
orangeFont.setColor(BaseColor.ORANGE);
String title = "巡检信息";
Paragraph paragraph = new Paragraph();
paragraph.setAlignment(Element.ALIGN_CENTER);
paragraph.add(new Chunk(title, fontZH).setLocalDestination(title));
// paragraph.add(new Chunk(title, new Font(bfChinese, 20F, Font.BOLD)).setLocalDestination(title));
document.add(paragraph);
document.add(new Paragraph("\n"));
PdfPTable table = new PdfPTable(2);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
float[] widths = {20f, 90f};
table.setWidths(widths);
PdfPCell cell;
cell = new PdfPCell(new Paragraph("巡检名称", fontZH));
setAndAddCellStyle(table, cell);
cell = new PdfPCell(new Paragraph(record.getName(), fontZH));
setAndAddCellStyle(table, cell);
cell = new PdfPCell(new Paragraph("巡检类型", fontZH));
setAndAddCellStyle(table, cell);
Integer recordType = record.getType();
String typeText = "-";
if (recordType == 0) {
typeText = "快速巡检-脚本";
} else if (recordType == 1) {
typeText = "常规巡检";
} else if (recordType == 2) {
typeText = "定时巡检";
}
cell = new PdfPCell(new Paragraph(typeText, fontZH));
setAndAddCellStyle(table, cell);
cell = new PdfPCell(new Paragraph("执行人员", fontZH));
setAndAddCellStyle(table, cell);
cell = new PdfPCell(new Paragraph(record.getUserName(), fontZH));
setAndAddCellStyle(table, cell);
cell = new PdfPCell(new Paragraph("巡检状态", fontZH));
setAndAddCellStyle(table, cell);
Integer recordStatus = record.getStatus();
if (recordStatus == 0) {
cell = new PdfPCell(new Paragraph("启动中", fontZH));
} else if (recordStatus == 1) {
cell = new PdfPCell(new Paragraph("执行中", fontZH));
} else if (recordStatus == 2) {
cell = new PdfPCell(new Paragraph("成功", greenFont));
} else if (recordStatus == 3) {
cell = new PdfPCell(new Paragraph("错误", redFont));
} else {
cell = new PdfPCell(new Paragraph("-", fontZH));
}
setAndAddCellStyle(table, cell);
cell = new PdfPCell(new Paragraph("告警状态", fontZH));
setAndAddCellStyle(table, cell);
Boolean recordWarning = record.getWarning();
if (!recordWarning) {
cell = new PdfPCell(new Paragraph("正常", greenFont));
} else {
cell = new PdfPCell(new Paragraph("告警", orangeFont));
}
setAndAddCellStyle(table, cell);
cell = new PdfPCell(new Paragraph("创建时间", fontZH));
setAndAddCellStyle(table, cell);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String createTime = simpleDateFormat.format(record.getCreateTime());
cell = new PdfPCell(new Paragraph(createTime, fontZH));
setAndAddCellStyle(table, cell);
cell = new PdfPCell(new Paragraph("执行时长", fontZH));
setAndAddCellStyle(table, cell);
Double totalTime = record.getTotalTime();
if (totalTime != null) {
cell = new PdfPCell(new Paragraph(totalTime.toString() + " 秒", fontZH));
} else {
cell = new PdfPCell(new Paragraph("-", fontZH));
}
setAndAddCellStyle(table, cell);
// 告警开始
List<InspectRecordWarning> warnList = record.getInspectRecordWarnings();
if (warnList.size() > 0) {
cell = new PdfPCell(new Paragraph("告警信息", fontZH));
setAndAddCellStyle(table, cell);
PdfPTable warnTable = new PdfPTable(3);
warnTable.setWidths(new float[]{22f, 23f, 55f});
setAndAddCellStyle(table, new PdfPCell(getWarningInfo(warnList, warnTable, fontZH)));
}
List<InspectRecordItem> list = record.getInspectRecordItems();
List<Object> objects = new ArrayList<>();
for (Object item : list) {
objects.add(item);
objects.removeAll(Collections.singleton(null));
}
if (objects.size() > 0) {
cell = new PdfPCell(new Paragraph("执行错误", fontZH));
setAndAddCellStyle(table, cell);
PdfPTable errorTable = new PdfPTable(3);
errorTable.setWidths(new float[]{22f, 23f, 55f});
setAndAddCellStyle(table, new PdfPCell(getErrorInfo(list, errorTable, fontZH)));
}
cell = new PdfPCell(new Paragraph("执行详情", fontZH));
setAndAddCellStyle(table, cell);
PdfPTable detailTable = new PdfPTable(3);
detailTable.setWidths(new float[]{22f, 23f, 55f});
setAndAddCellStyle(table, new PdfPCell(getDetailInfo(list, detailTable, fontZH)));
// 添加大表格
document.add(table);
// 第七步,关闭document
document.close();
System.out.println("导出pdf成功~");
}
private PdfPTable getWarningInfo(List<InspectRecordWarning> list, PdfPTable warningTable, Font fontZH) {
PdfPCell cell;
cell = new PdfPCell(new Paragraph("主机ip", fontZH));
setCellCenter(cell);
warningTable.addCell(cell);
cell = new PdfPCell(new Paragraph("指标项", fontZH));
setCellCenter(cell);
cell = new PdfPCell(new Paragraph("告警信息", fontZH));
setCellCenter(cell);
warningTable.addCell(cell);
for (InspectRecordWarning item : list) {
cell = new PdfPCell(new Paragraph(item.getIp(), fontZH));
setCellCenter(cell);
warningTable.addCell(cell);
cell = new PdfPCell(new Paragraph(item.getInspectItemName(), fontZH));
setCellCenter(cell);
warningTable.addCell(cell);
String content = item.getContent();
cell = new PdfPCell(new Paragraph(content != null ? content : "-", fontZH));
setCellCenter(cell);
warningTable.addCell(cell);
}
return warningTable;
}
/*
获取执行错误信息
*/
private PdfPTable getErrorInfo(List<InspectRecordItem> list, PdfPTable errorTable, Font fontZH) {
PdfPCell cell;
cell = new PdfPCell(new Paragraph("主机ip", fontZH));
setCellCenter(cell);
errorTable.addCell(cell);
cell = new PdfPCell(new Paragraph("指标项", fontZH));
setCellCenter(cell);
errorTable.addCell(cell);
cell = new PdfPCell(new Paragraph("执行错误信息", fontZH));
setCellCenter(cell);
errorTable.addCell(cell);
for (InspectRecordItem item : list) {
cell = new PdfPCell(new Paragraph(item.getIp(), fontZH));
setCellCenter(cell);
errorTable.addCell(cell);
cell = new PdfPCell(new Paragraph(item.getInspectItemName(), fontZH));
setCellCenter(cell);
errorTable.addCell(cell);
String errorInfo = item.getScriptErrorInfo();
cell = new PdfPCell(new Paragraph(errorInfo !=null ? errorInfo : "-", fontZH));
setCellCenter(cell);
errorTable.addCell(cell);
}
return errorTable;
}
private PdfPTable getDetailInfo(List<InspectRecordItem> list, PdfPTable detailTable, Font fontZH) {
PdfPCell cell;
cell = new PdfPCell(new Paragraph("主机ip", fontZH));
setCellCenter(cell);
detailTable.addCell(cell);
cell = new PdfPCell(new Paragraph("指标项", fontZH));
setCellCenter(cell);
detailTable.addCell(cell);
cell = new PdfPCell(new Paragraph("详情", fontZH));
setCellCenter(cell);
detailTable.addCell(cell);
for (InspectRecordItem item : list) {
cell = new PdfPCell(new Paragraph(item.getIp(), fontZH));
setCellCenter(cell);
detailTable.addCell(cell);
cell = new PdfPCell(new Paragraph(item.getInspectItemName(), fontZH));
setCellCenter(cell);
detailTable.addCell(cell);
// 详情
String log = item.getLog();
if (log != null) {
JSONObject logJsonObj = JSONObject.parseObject(log);
Set<String> logSet = logJsonObj.keySet();
Object logObj;
String logStr = "";
for (String key : logSet) {
logObj = logJsonObj.get(key);
logStr += key + " : " + logObj.toString() + "\n";
}
cell = new PdfPCell(new Paragraph("".equals(logStr) ? "-" : logStr, fontZH));
} else {
cell = new PdfPCell(new Paragraph("-", fontZH));
}
setCellCenter(cell);
detailTable.addCell(cell);
}
return detailTable;
}
private void setAndAddCellStyle(PdfPTable table, PdfPCell cell) {
cell.setMinimumHeight(30.0F);
cell.setPaddingTop(10f);
cell.setPaddingBottom(10f);
setCellCenter(cell);
cell.setBorder(Rectangle.NO_BORDER);
table.addCell(cell);
}
private void setCellCenter(PdfPCell cell) {
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
}
}
Excel导出
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@RestController
public class InspectRecordExcelController extends BaseController {
@Autowired
InspectRecordService inspectRecordService;
public static final short BOLD_FONT = 20;
public static final short NORMAL_FONT = 12;
// 创建表头
@RequestMapping(value = "/inspect/record/excel/{id}", method = {RequestMethod.GET})
@ResponseBody
public void createTitle(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
sheet.setColumnWidth(0, 16 * 256);
sheet.setColumnWidth(1, 20 * 256);
sheet.setColumnWidth(2, 30 * 256);
sheet.setColumnWidth(3, 40 * 256);
InspectRecord record = inspectRecordService.get(id).getData();
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 3));
for (int i = 2; i < 9; i++) {
sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 3));
}
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellStyle(getStyle(workbook, BOLD_FONT, true));
cell.setCellValue("巡检信息");
HSSFRow row2 = sheet.createRow(2);
HSSFCell cell2 = row2.createCell(0);
cell2.setCellValue("巡检名称");
cell2.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell2 = row2.createCell(1);
cell2.setCellValue(record.getName());
cell2.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
HSSFRow row3 = sheet.createRow(3);
HSSFCell cell3 = row3.createCell(0);
cell3.setCellValue("巡检类型");
cell3.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell3 = row3.createCell(1);
Integer recordType = record.getType();
if (recordType == 0) {
cell3.setCellValue("快速巡检-脚本");
} else if (recordType == 1) {
cell3.setCellValue("常规巡检");
} else if (recordType == 2) {
cell3.setCellValue("定时巡检");
} else {
cell3.setCellValue("-");
}
cell3.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
HSSFRow row4 = sheet.createRow(4);
HSSFCell cell4 = row4.createCell(0);
cell4.setCellValue("用户名");
cell4.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell4 = row4.createCell(1);
cell4.setCellValue(record.getUserName());
cell4.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
HSSFRow row5 = sheet.createRow(5);
HSSFCell cell5 = row5.createCell(0);
cell5.setCellValue("巡检状态");
cell5.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell5 = row5.createCell(1);
Integer status = record.getStatus();
if (status == 0) {
cell5.setCellValue("启动中");
cell5.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
} else if (status == 1) {
cell5.setCellValue("执行中");
cell5.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
} else if (status == 2) {
setStatus(workbook, cell5, "成功", HSSFColor.GREEN.index);
} else if (status == 3) {
setStatus(workbook, cell5, "错误", HSSFColor.RED.index);
} else {
cell5.setCellValue("-");
cell5.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
}
HSSFRow row6 = sheet.createRow(6);
HSSFCell cell6 = row6.createCell(0);
cell6.setCellValue("告警状态");
cell6.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell6 = row6.createCell(1);
if (!record.getWarning()) {
setStatus(workbook, cell6, "正常", HSSFColor.GREEN.index);
} else {
setStatus(workbook, cell6, "告警", HSSFColor.ORANGE.index);
}
HSSFRow row7 = sheet.createRow(7);
HSSFCell cell7 = row7.createCell(0);
cell7.setCellValue("创建时间");
cell7.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell7 = row7.createCell(1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cell7.setCellValue(sdf.format(record.getCreateTime()));
cell7.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
HSSFRow row8 = sheet.createRow(8);
HSSFCell cell8 = row8.createCell(0);
cell8.setCellValue("执行时长");
cell8.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell8 = row8.createCell(1);
Double totalTime = record.getTotalTime();
if (totalTime != null) {
cell8.setCellValue(totalTime + "秒");
} else {
cell8.setCellValue("-");
}
cell8.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
// 嵌套
List<InspectRecordWarning> warnings = record.getInspectRecordWarnings();
int warnSize = warnings.size();
if (warnSize > 0) { // 如果有告警信息才显示对象
sheet.addMergedRegion(new CellRangeAddress(10, 10 + warnSize, 0, 0));
HSSFRow row10 = sheet.createRow(10);
HSSFCell cell10 = row10.createCell(0);
cell10.setCellValue("告警信息");
cell10.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell10 = row10.createCell(1);
cell10.setCellValue("主机ip");
cell10.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell10 = row10.createCell(2);
cell10.setCellValue("指标项");
cell10.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell10 = row10.createCell(3);
cell10.setCellValue("告警信息");
cell10.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
for (int i = 0; i < warnSize;) {
InspectRecordWarning warning = warnings.get(i);
i += 1;
HSSFRow row11 = sheet.createRow(10 + i);
HSSFCell cell11 = row11.createCell(1);
cell11.setCellValue(warning.getIp());
cell11.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
cell11 = row11.createCell(2);
cell11.setCellValue(warning.getInspectItemName());
cell11.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
cell11 = row11.createCell(3);
String warnInfo = warning.getContent();
cell11.setCellValue(warnInfo == null ? "-" : warnInfo);
cell11.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
}
}
// 错误开始
List<InspectRecordItem> list = record.getInspectRecordItems();
int listSize = list.size();
List<Object> objects = new ArrayList<>();
for (InspectRecordItem item : list) {
objects.add(item);
objects.removeAll(Collections.singleton(null));
}
int errorSize = objects.size();
if (objects.size() > 0) { // 如果有错误信息才展示列表
sheet.addMergedRegion(new CellRangeAddress(11 + warnSize, 11 + warnSize + errorSize, 0, 0));
HSSFRow row12 = sheet.createRow(11 + warnSize);
HSSFCell cell12 = row12.createCell(0);
cell12.setCellValue("错误信息");
cell12.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell12 = row12.createCell(1);
cell12.setCellValue("主机ip");
cell12.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell12 = row12.createCell(2);
cell12.setCellValue("指标项");
cell12.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell12 = row12.createCell(3);
cell12.setCellValue("错误信息");
cell12.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
for (int i = 0; i < listSize; ) {
InspectRecordItem item = list.get(i);
i += 1;
HSSFRow row13 = sheet.createRow(11 + i + warnSize);
HSSFCell cell13 = row13.createCell(1);
cell13.setCellValue(item.getIp());
cell13.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
cell13 = row13.createCell(2);
cell13.setCellValue(item.getInspectItemName());
cell13.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
cell13 = row13.createCell(3);
String errorInfo = item.getScriptErrorInfo();
cell13.setCellValue(errorInfo == null ? "-" : errorInfo);
cell13.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
}
}
// 详情必须显示
sheet.addMergedRegion(new CellRangeAddress(12 + warnSize + errorSize, 12 + warnSize + errorSize + listSize, 0,
0));
HSSFRow row13 = sheet.createRow(12 + warnSize + errorSize);
HSSFCell cell14 = row13.createCell(0);
cell14.setCellValue("详细信息");
cell14.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell14 = row13.createCell(1);
cell14.setCellValue("主机ip");
cell14.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell14 = row13.createCell(2);
cell14.setCellValue("指标项");
cell14.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
cell14 = row13.createCell(3);
cell14.setCellValue("详细信息");
cell14.setCellStyle(getStyle(workbook, NORMAL_FONT, true));
for (int i = 0; i < listSize;) {
InspectRecordItem item = list.get(i);
i += 1;
HSSFRow row14 = sheet.createRow(12 + i + warnSize + errorSize);
HSSFCell cell15 = row14.createCell(1);
cell15.setCellValue(item.getIp());
cell15.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
cell15 = row14.createCell(2);
cell15.setCellValue(item.getInspectItemName());
cell15.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
cell15 = row14.createCell(3);
String log = item.getLog();
if (log != null) {
JSONObject logJsonObj = JSONObject.parseObject(log);
Set<String> logSet = logJsonObj.keySet();
Object logObj;
String logStr = "";
for (String key : logSet) {
logObj = logJsonObj.get(key);
logStr += key + ":" + logObj.toString() + "\n";
}
cell15.setCellValue("".equals(logStr) ? "-" : logStr);
} else {
cell15.setCellValue("-");
}
cell15.setCellStyle(getStyle(workbook, NORMAL_FONT, false));
}
String filename = record.getName() + ".xls";
buildExcelDocument(filename, workbook, response);
}
/**
* @param cellValue 单元格填充值
* @param workbook 工作表
* @param cell 单元格
* @param colorIndex 单元格字体颜色
*/
private void setStatus(HSSFWorkbook workbook, HSSFCell cell, String cellValue, short colorIndex) {
cell.setCellValue(cellValue);
HSSFFont font = workbook.createFont();
font.setColor(colorIndex);
HSSFCellStyle style = getStyle(workbook, NORMAL_FONT, false);
style.setFont(font);
cell.setCellStyle(style);
}
/**
* 标题或者第一列数据信息单元格样式
*
* @param fontHeight 标题20, 第一列12,第二列12
*/
private HSSFCellStyle getStyle(HSSFWorkbook workbook, short fontHeight, boolean isBold) {
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((fontHeight));
font.setBold(isBold);
font.setFontName("宋体");
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setWrapText(true);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
// 浏览器下载excel
private void buildExcelDocument(String filename, HSSFWorkbook workbook, HttpServletResponse response) throws
IOException {
// 清空response,否则可能会对程序有影响,因为在此之前有可能也用到了response,若不reset,后面的setCntentoType()有可能失效
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
OutputStream os = response.getOutputStream();
workbook.write(os);
os.flush();
os.close();
}
}