123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455 |
- 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<PageInfo<HashMap<String, Object>>> getList(@RequestBody WellInfoParams params) throws Exception {
- PageInfo<HashMap<String, Object>> result = wellInfoService.getList(params.getPage(), params.getRows(), params);
- return RespGenerstor.success(result);
- }
- @ResponseBody
- @GetMapping("/getMapList")
- public BaseResponse<PageInfo<HashMap<String, Object>>> getMapList(@RequestParam("page") int page, @RequestParam("rows") int rows,
- WellInfoParams params) throws Exception {
- PageInfo<HashMap<String, Object>> 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<String, Object> wellInfo = wellInfoService.getWellInfo(well_id);
- List<HashMap<String, Object>> boreholeInterList = wellInfoService.selectBoreholeInterList(well_id);
- List<HashMap<String, Object>> testHistoryList = wellInfoService.selectTestHistoryList(well_id);
- List<HashMap<String, Object>> testHistorySummary = wellInfoService.selectTestHistorySummary(well_id);
- HashMap<String, Object> lastTestHistory = wellInfoService.getLastTestHistory(well_id);
- List<HashMap<String, Object>> analyticalAssaysList = wellInfoService.selectAnalyticalAssaysList(well_id);
- List<HashMap<String, Object>> analyticalAssaysSummary = wellInfoService.selectAnalyticalAssaysSummary(well_id);
- List<HashMap<String, Object>> historyAssignmentList = wellInfoService.selectHistoryAssignmentList(well_id);
- List<HashMap<String, Object>> historyAssignmentSummary = wellInfoService.selectHistoryAssignmentSummary(well_id);
- HashMap<String, Object> lastHistoryAssignment = wellInfoService.getLastHistoryAssignment(well_id);
- List<HashMap<String, Object>> dataIndexList = wellInfoService.selectDataIndexList(well_id);
- HashMap<String, Object> 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<HashMap<String, Object>> 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<String, String> 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<CellRangeAddress> 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<Map<String, Object>> mapList = getPicturesFromHSSFSheet(source);
- XSSFDrawing drawing = destination.createDrawingPatriarch();
- for (Map<String, Object> 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<Map<String, Object>> getPicturesFromHSSFSheet(HSSFSheet sheet) {
- List<Map<String, Object>> mapList = new ArrayList<>();
- if (sheet.getDrawingPatriarch() == null) {
- return mapList;
- }
- List<HSSFShape> list = sheet.getDrawingPatriarch().getChildren();
- for (HSSFShape shape : list) {
- if (shape instanceof HSSFPicture) {
- Map<String, Object> 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;
- }
- }
|