package com.bowintek.practice.controller; import com.alibaba.druid.support.logging.Log; import com.aspose.cells.License; import com.aspose.cells.PdfSaveOptions; import com.aspose.cells.SaveFormat; import com.aspose.cells.SaveOptions; import com.bowintek.practice.AppConfig; import com.bowintek.practice.filter.exception.BaseResponse; import com.bowintek.practice.filter.exception.RespGenerstor; import com.bowintek.practice.model.WlUserExpendSetting; import com.bowintek.practice.services.service.AccountService; import com.bowintek.practice.services.service.OrganizationService; import com.bowintek.practice.services.service.WellInfoService; import com.bowintek.practice.util.RemoteHelper; import com.bowintek.practice.vo.query.WellInfoParams; import com.github.pagehelper.PageInfo; import lombok.extern.slf4j.Slf4j; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.extractor.WordExtractor; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.util.Units; import org.apache.poi.xssf.usermodel.*; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.*; @RestController @RequestMapping(value = "/api/wellInfo") @Slf4j public class WellInfoController { @Autowired private WellInfoService wellInfoService; @Autowired private OrganizationService organizationService; @Autowired private AccountService accountService; @Autowired private RemoteHelper remoteHelper; @Autowired private AppConfig appConfig; @ResponseBody @PostMapping("/getList") public BaseResponse>> getList(@RequestBody WellInfoParams params) throws Exception { PageInfo> result = wellInfoService.getList(params.getPage(), params.getRows(), params); return RespGenerstor.success(result); } @ResponseBody @GetMapping("/getMapList") public BaseResponse>> getMapList(@RequestParam("page") int page, @RequestParam("rows") int rows, WellInfoParams params) throws Exception { PageInfo> result = wellInfoService.getMapList(page, rows, params); return RespGenerstor.success(result); } @GetMapping("/getOrganizationTree") public BaseResponse getOrganizationTree() { return RespGenerstor.success(organizationService.getListTree("HBlQAIBGob")); } @GetMapping("/getWellInfo") public BaseResponse getWellInfo(String well_id) { HashMap wellInfo = wellInfoService.getWellInfo(well_id); List> boreholeInterList = wellInfoService.selectBoreholeInterList(well_id); List> testHistoryList = wellInfoService.selectTestHistoryList(well_id); List> testHistorySummary = wellInfoService.selectTestHistorySummary(well_id); HashMap lastTestHistory = wellInfoService.getLastTestHistory(well_id); List> analyticalAssaysList = wellInfoService.selectAnalyticalAssaysList(well_id); List> analyticalAssaysSummary = wellInfoService.selectAnalyticalAssaysSummary(well_id); List> historyAssignmentList = wellInfoService.selectHistoryAssignmentList(well_id); List> historyAssignmentSummary = wellInfoService.selectHistoryAssignmentSummary(well_id); HashMap lastHistoryAssignment = wellInfoService.getLastHistoryAssignment(well_id); List> dataIndexList = wellInfoService.selectDataIndexList(well_id); HashMap result = new HashMap<>(); result.put("dataModel", wellInfo); result.put("boreholeInterList", boreholeInterList);//业务解释列表 result.put("testHistoryList", testHistoryList);//测试历史列表 result.put("testHistorySummary", testHistorySummary);//测试历史汇总 result.put("lastTestHistory", lastTestHistory);//最后一次测试历史 result.put("analyticalAssaysList", analyticalAssaysList);//分析化验列表 result.put("analyticalAssaysSummary", analyticalAssaysSummary);//分析化验汇总 result.put("historyAssignmentList", historyAssignmentList);//作业简史列表 result.put("historyAssignmentSummary", historyAssignmentSummary);//作业简史汇总 result.put("lastHistoryAssignment", lastHistoryAssignment);//最后一次作业简史记录 result.put("dataIndexList", dataIndexList); return RespGenerstor.success(result); } @ResponseBody @PostMapping("/saveExpendSetting") public BaseResponse saveExpendSetting(@RequestBody WlUserExpendSetting model) { int count = 0; try { model.setUserID(accountService.getLoginUserID()); count = wellInfoService.saveExpendSetting(model); } catch (Exception e) { return RespGenerstor.fail("-1", "程序异常:" + e.getMessage()); } return RespGenerstor.success(count); } @GetMapping("/getExpendSetting") public BaseResponse getExpendSetting(String wellId) { return RespGenerstor.success(wellInfoService.getExpendSetting(wellId, accountService.getLoginUserID())); } @GetMapping("/getWellDocumentList") public BaseResponse getWellDocumentList(String wellId) { List> dataIndexList = wellInfoService.selectDataIndexList(wellId); return RespGenerstor.success(dataIndexList); } @GetMapping("/getConstructUnitTree") public BaseResponse getConstructUnitTree() { return RespGenerstor.success(wellInfoService.getConstructUnitTree()); } @GetMapping("/downFile") public void downFile(HttpServletResponse response, Integer isShow, String filePath, String fileName) throws IOException { Map getParams = new HashMap<>(); getParams.put("fileName", fileName); getParams.put("filePath", filePath); String reData = remoteHelper.getJson(getParams, appConfig.hdfshelperurl + "read", "UTF-8"); byte[] bytes = Base64.getMimeDecoder().decode(reData); OutputStream os = response.getOutputStream(); if (isShow != null && 1 == isShow) { //如果是预览需要把doc转docx,xls转xlsx,前端预览插件不支持这两种格式 if (fileName.toLowerCase().endsWith(".doc")) { bytes = doc2Docx(bytes); } else if (fileName.toLowerCase().endsWith(".xls")) { bytes = xls2pdf(bytes); } } response.setContentType("multipart/form-data;charset=UTF-8"); response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));// 设置文件名 response.setHeader("Content-Length", String.valueOf(bytes.length)); os.write(bytes); if (null != os) { os.flush(); os.close(); } } private byte[] xls2pdf(byte[] bytes) { long old = System.currentTimeMillis(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { License aposeLic = new License(); InputStream license = ClassLoader.getSystemClassLoader().getResourceAsStream("license-cell.xml"); aposeLic.setLicense(license); com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(new ByteArrayInputStream(bytes)); PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); pdfSaveOptions.setOnePagePerSheet(true); int[] autoDrawSheets = {3}; //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。 autoDraw(wb, autoDrawSheets); wb.save(outputStream, pdfSaveOptions); bytes = outputStream.toByteArray(); outputStream.flush(); long now = System.currentTimeMillis(); log.info("共耗时:{}", ((now - old) / 1000.0)); } catch (Exception e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (Exception e) { e.printStackTrace(); } ; } } return bytes; } /** * 设置打印的sheet 自动拉伸比例 * * @param wb * @param page 自动拉伸的页的sheet数组 */ public static void autoDraw(com.aspose.cells.Workbook wb, int[] page) { if (null != page && page.length > 0) { for (int i = 0; i < page.length; i++) { wb.getWorksheets().get(i).getHorizontalPageBreaks().clear(); wb.getWorksheets().get(i).getVerticalPageBreaks().clear(); } } } private byte[] xls2xlsx(byte[] bytes) throws IOException { InputStream fis = new ByteArrayInputStream(bytes); try (HSSFWorkbook xlsWorkbook = new HSSFWorkbook(fis); XSSFWorkbook xlsxWorkbook = new XSSFWorkbook()) { for (int i = 0; i < xlsWorkbook.getNumberOfSheets(); i++) { HSSFSheet xlsSheet = xlsWorkbook.getSheetAt(i); XSSFSheet xlsxSheet = xlsxWorkbook.createSheet(xlsSheet.getSheetName()); for (int j = 0; j <= xlsSheet.getLastRowNum(); j++) { HSSFRow xlsRow = xlsSheet.getRow(j); if (xlsRow == null) { continue; } XSSFRow xlsxRow = xlsxSheet.createRow(xlsRow.getRowNum()); for (int k = 0; k < xlsRow.getLastCellNum(); k++) { HSSFCell xlsCell = xlsRow.getCell(k); if (xlsCell == null) { continue; } XSSFCell xlsxCell = xlsxRow.createCell(xlsCell.getColumnIndex()); setCellValue(xlsxCell, xlsCell, xlsWorkbook); copyCellStyle(xlsxWorkbook, xlsxCell, xlsWorkbook, xlsCell); } } // 复制单元格合并信息 List mergedRegions = xlsSheet.getMergedRegions(); for (CellRangeAddress mergedRegion : mergedRegions) { CellRangeAddress targetMergedRegion = new CellRangeAddress( mergedRegion.getFirstRow(), mergedRegion.getLastRow(), mergedRegion.getFirstColumn(), mergedRegion.getLastColumn() ); xlsxSheet.addMergedRegion(targetMergedRegion); } // 拷贝图片 copyPicture(xlsSheet, xlsxSheet); // 复制列宽 int columnCount = 0; if (xlsxSheet.getRow(0) != null) { // 假设第一行包含所有列,根据第一行的列数获取列数 columnCount = xlsxSheet.getRow(0).getLastCellNum(); } for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { xlsxSheet.setColumnWidth(columnIndex, xlsSheet.getColumnWidth(columnIndex)); } } try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();) { xlsxWorkbook.write(outputStream); bytes = outputStream.toByteArray(); outputStream.close(); xlsxWorkbook.close(); } log.info("xls文件转换完成"); } catch (IOException e) { e.printStackTrace(); } return bytes; } // 拷贝图片 public void copyPicture(HSSFSheet source, XSSFSheet destination) { // 获取sheet中的图片信息 List> mapList = getPicturesFromHSSFSheet(source); XSSFDrawing drawing = destination.createDrawingPatriarch(); for (Map pictureMap : mapList) { HSSFClientAnchor hssfClientAnchor = (HSSFClientAnchor) pictureMap.get("pictureAnchor"); HSSFRow startRow = source.getRow(hssfClientAnchor.getRow1()); float startRowHeight = startRow == null ? source.getDefaultRowHeightInPoints() : startRow.getHeightInPoints(); HSSFRow endRow = source.getRow(hssfClientAnchor.getRow1()); float endRowHeight = endRow == null ? source.getDefaultRowHeightInPoints() : endRow.getHeightInPoints(); // hssf的单元格,每个单元格无论宽高,都被分为 宽 1024个单位 高 256个单位。 // 32.00f 为默认的单元格单位宽度 单元格宽度 / 默认宽度 为像素宽度 XSSFClientAnchor xssfClientAnchor = drawing.createAnchor( (int) (source.getColumnWidth(hssfClientAnchor.getCol1()) / 32.00f / 1024 * hssfClientAnchor.getDx1() * Units.EMU_PER_PIXEL), (int) (startRowHeight / 256 * hssfClientAnchor.getDy1() * Units.EMU_PER_POINT), (int) (source.getColumnWidth(hssfClientAnchor.getCol2()) / 32.00f / 1024 * hssfClientAnchor.getDx2() * Units.EMU_PER_PIXEL), (int) (endRowHeight / 256 * hssfClientAnchor.getDy2() * Units.EMU_PER_POINT), hssfClientAnchor.getCol1(), hssfClientAnchor.getRow1(), hssfClientAnchor.getCol2(), hssfClientAnchor.getRow2()); xssfClientAnchor.setAnchorType(hssfClientAnchor.getAnchorType()); drawing.createPicture(xssfClientAnchor, destination.getWorkbook().addPicture((byte[]) pictureMap.get("pictureByteArray"), Integer.parseInt(pictureMap.get("pictureType").toString()))); } } /** * 获取图片和位置 (xls) */ public List> getPicturesFromHSSFSheet(HSSFSheet sheet) { List> mapList = new ArrayList<>(); if (sheet.getDrawingPatriarch() == null) { return mapList; } List list = sheet.getDrawingPatriarch().getChildren(); for (HSSFShape shape : list) { if (shape instanceof HSSFPicture) { Map map = new HashMap<>(); HSSFPicture picture = (HSSFPicture) shape; HSSFClientAnchor cAnchor = picture.getClientAnchor(); HSSFPictureData pdata = picture.getPictureData(); map.put("pictureAnchor", cAnchor); map.put("pictureByteArray", pdata.getData()); map.put("pictureType", pdata.getPictureType()); map.put("pictureSize", picture.getImageDimension()); mapList.add(map); } } return mapList; } private void setCellValue(Cell newCell, Cell oldCell, HSSFWorkbook xlsWorkbook) { if (oldCell == null) { return; } try { switch (oldCell.getCellType()) { case STRING: newCell.setCellValue(oldCell.getStringCellValue()); break; case NUMERIC: if (DateUtil.isCellDateFormatted(oldCell)) { newCell.setCellValue(oldCell.getDateCellValue()); } else { newCell.setCellValue(oldCell.getNumericCellValue()); } break; case BLANK: newCell.setCellType(CellType.BLANK); break; case BOOLEAN: newCell.setCellValue(oldCell.getBooleanCellValue()); break; case FORMULA: // HSSFFormulaEvaluator evaluator=new HSSFFormulaEvaluator(xlsWorkbook); // CellValue tempCellValue = evaluator.evaluate(oldCell); newCell.setCellValue(oldCell.getNumericCellValue()); break; default: } } catch (Exception ex) { System.out.println("setCellValue出错:" + ex.getMessage()); log.info("setCellValue出错:" + ex.getMessage()); } } private void copyCellStyle(XSSFWorkbook xssfWorkbook, XSSFCell newCell, HSSFWorkbook hssfWorkbook, HSSFCell oldCell) { HSSFCellStyle oldCellStyle = oldCell.getCellStyle(); // 创建一个XSSFCellStyle(新Excel格式) XSSFCellStyle newCellStyle = xssfWorkbook.createCellStyle(); // 复制对齐方式 newCellStyle.setAlignment(oldCellStyle.getAlignment()); newCellStyle.setVerticalAlignment(oldCellStyle.getVerticalAlignment()); // 复制字体属性 XSSFFont newFont = xssfWorkbook.createFont(); HSSFFont oldFont = oldCellStyle.getFont(hssfWorkbook); newFont.setFontName(oldFont.getFontName()); newFont.setFontHeightInPoints(oldFont.getFontHeightInPoints()); newFont.setColor(oldFont.getColor()); newCellStyle.setFont(newFont); // 复制填充颜色 newCellStyle.setFillPattern(oldCellStyle.getFillPattern()); newCellStyle.setFillForegroundColor(oldCellStyle.getFillForegroundColor()); newCellStyle.setFillBackgroundColor(oldCellStyle.getFillBackgroundColor()); // 复制数据格式 newCellStyle.setDataFormat(oldCellStyle.getDataFormat()); // 文本换行 newCellStyle.setWrapText(oldCellStyle.getWrapText()); newCellStyle.setBorderBottom(oldCellStyle.getBorderBottom()); newCellStyle.setBorderLeft(oldCellStyle.getBorderLeft()); newCellStyle.setBorderRight(oldCellStyle.getBorderRight()); newCellStyle.setBorderTop(oldCellStyle.getBorderTop()); newCellStyle.setBottomBorderColor(oldCellStyle.getBottomBorderColor()); newCellStyle.setDataFormat(oldCellStyle.getDataFormat()); newCellStyle.setFillBackgroundColor(oldCellStyle.getFillBackgroundColor()); newCellStyle.setFillPattern(oldCellStyle.getFillPattern()); newCellStyle.setHidden(oldCellStyle.getHidden()); newCellStyle.setIndention(oldCellStyle.getIndention()); newCellStyle.setLeftBorderColor(oldCellStyle.getLeftBorderColor()); newCellStyle.setLocked(oldCellStyle.getLocked()); newCellStyle.setQuotePrefixed(oldCellStyle.getQuotePrefixed()); newCellStyle.setReadingOrder(ReadingOrder.forLong(oldCellStyle.getReadingOrder())); newCellStyle.setRightBorderColor(oldCellStyle.getRightBorderColor()); newCellStyle.setRotation(oldCellStyle.getRotation()); newCell.setCellStyle(newCellStyle); } private byte[] doc2Docx(byte[] bytes) throws IOException { try { // 将doc文件的内容读取到XWPFDocument对象中 InputStream fis = new ByteArrayInputStream(bytes); HWPFDocument doc = new HWPFDocument(fis); WordExtractor wordExtractor = new WordExtractor(doc); String text = wordExtractor.getText(); XWPFDocument docx = new XWPFDocument(); XWPFParagraph paragraph = docx.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(text); // 保存XWPFDocument对象到docx文件中 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); docx.write(outputStream); bytes = outputStream.toByteArray(); doc.close(); docx.close(); outputStream.close(); } catch (Exception ex) { log.info("doc2Docx文件转换失败:" + ex.getMessage()); } return bytes; } }