利用aspose-cells解決 excel預覽的摺疊問題

1、jar包

<dependency>
			<groupId>com.aspose.cells</groupId>
			<artifactId>aspose-cells</artifactId>
			<version>8.5.2</version>
		</dependency>

2、在根目錄放:license.xml 

具體資源請下載:

https://download.csdn.net/download/gzc_870301/12403483

/**
 *@description excel轉pdf  解決摺疊問題(列太多)
 * @author gezc30201
 * @date 2020/5/9
 */
@Slf4j
public class ExcelToPdfUtil {

    /**
     *@description 獲取license 去除水印
     * @return
     * @author gezc30201
     * @date 2020/5/9
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = ExcelToPdfUtil.class.getClassLoader().getResourceAsStream("\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *@description excel 轉爲pdf 輸出。
     * @param sourceFilePath   excel文件
     * @param desFilePathd   pad 輸出文件目錄
     * @return void
     * @author gezc30201
     * @date 2020/5/9
     */
    public static void excel2pdf(String sourceFilePath, String desFilePathd ){
        if (!getLicense()) { // 驗證License 若不驗證則轉化出的pdf文檔會有水印產生
            return;
        }
        try {
            Workbook wb = new Workbook(sourceFilePath); // 原始excel路徑

            FileOutputStream fileOS = new FileOutputStream(desFilePathd);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);//縮放到一個頁面(如果列太多 太長)

            /**
             * 自動縮放了
             */
            /* int[] autoDrawSheets={3};
            //當excel中對應的sheet頁寬度太大時,在PDF中會拆斷並分頁。此處等比縮放。
            autoDraw(wb,autoDrawSheets);*/

            /**
             * 以下代碼打開則只顯示第一個sheet
             */
              /*int[] showSheets={0};
            //隱藏workbook中不需要的sheet頁。
             printSheetPage(wb,showSheets);*/
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();

        } catch (Exception e) {
            log.error(ExceptionUtils.getTrace(e));
            throw new RuntimeException();
        }
    }

    /**
     *@description 描述
     * @param inbytes excel輸入流的字節數組
     * @return byte[]
     * @author gezc30201
     * @date 2020/5/9
     */
    public static byte[] excel2pdf(byte[] inbytes ) throws IOException {
        if (!getLicense()) { // 驗證License 若不驗證則轉化出的pdf文檔會有水印產生
            return null;
        }
        ByteArrayOutputStream pdfstream=null;
        try {
            Workbook wb = new Workbook(new ByteArrayInputStream(inbytes));// 原始excel流
             pdfstream = new ByteArrayOutputStream();  //保存轉成pdf的流
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);//縮放到一個頁面(如果列太多 太長)

            wb.save(pdfstream, pdfSaveOptions);
            byte[] outbytes = pdfstream.toByteArray();
            return outbytes;
        } catch (Exception e) {
            log.error(ExceptionUtils.getTrace(e));
            throw new RuntimeException();
        }finally {
            if (pdfstream!=null){
                pdfstream.close();
            }
        }
    }

    /**
     *@description 設置打印的sheet 自動拉伸比例
     * @param wb
    	 * @param page 自動拉伸的頁的sheet數組
     * @return void
     * @author gezc30201
     * @date 2020/5/9
     */
    public static void autoDraw(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();
            }
        }
    }


    /**
     * 隱藏workbook中不需要的sheet頁。
     * @param wb
     * @param page 顯示頁的sheet數組
     */
    public static void printSheetPage(Workbook wb, int[] page){
        for (int i= 1; i < wb.getWorksheets().getCount(); i++)  {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if (null==page||page.length==0){
            wb.getWorksheets().get(0).setVisible(true);
        }else{
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }


    /*public static void main(String[] args) {
        String sourceFilePath="d:/test.xlsx";
        String desFilePath="d:/rest.pdf";
        excel2pdf(sourceFilePath, desFilePath);
    }*/
}

controller:

@GetMapping("/previewAttach")
	public void previewAttach(HttpServletResponse response, @RequestParam(value = "attach_id") String attachId)  {

		DownloadAttach downloadAttach = sysAttachService.downloadAttach(attachId).getResult();
		if (downloadAttach == null || downloadAttach.getBytes() == null) {
			log.warn("附件獲取爲空。附件id:" + attachId.replaceAll("[\r\n]", ""));
			throw new BaseBizException("-1", "附件不存在");
		}
		/*if (!".pdf".equals(downloadAttach.getFileSuffix())){6
			throw new BaseBizException("-1", "只有PDF可以預覽");
		}*/
		if (!DocEnum.PDF.getPointSuffix().equals(downloadAttach.getFileSuffix())&&!DocEnum.XLS.getPointSuffix().equals(downloadAttach.getFileSuffix())&&!DocEnum.XLSX.getPointSuffix().equals(downloadAttach.getFileSuffix())){
			try {
				downloadAttach.setBytes(Doc2PdfUtil.doc2pdf(downloadAttach.getFileSuffix().substring(1),downloadAttach.getBytes()));
			} catch (Exception e) {
				log.error(ExceptionUtils.getTrace(e));
				throw new BaseBizException("-1", "openoffice服務連接不上或者轉換pdf失敗");
			}
		}

		if (DocEnum.XLS.getPointSuffix().equals(downloadAttach.getFileSuffix())||DocEnum.XLSX.getPointSuffix().equals(downloadAttach.getFileSuffix())){
			try {
				downloadAttach.setBytes(ExcelToPdfUtil.excel2pdf(downloadAttach.getBytes()));
			} catch (IOException e) {
				log.error(ExceptionUtils.getTrace(e));
				throw new BaseBizException("-1", "excel轉換pdf失敗");
			}
		}

		OutputStream os = null;
		try {
			response.setHeader("content-length", String.valueOf(downloadAttach.getBytes().length));
			// 預覽
			response.setContentType("application/pdf;charset=utf-8");
			response.setHeader("content-disposition", "inline;filename=" +
			java.net.URLEncoder.encode(downloadAttach.getFileName(), "UTF-8"));
			os = response.getOutputStream();
			//os.write(downloadAttach.getBytes(),0,downloadAttach.getBytes().length);
			int lens = downloadAttach.getBytes().length;
			int flag = 0;
			while (lens > 0){
				os.write(Arrays.copyOfRange(downloadAttach.getBytes(),flag * DOWNLOAD_LENS,(lens > DOWNLOAD_LENS) ? (flag + 1) * DOWNLOAD_LENS : (flag * DOWNLOAD_LENS + lens)));
				flag ++;
				log.info(flag);
				lens -= DOWNLOAD_LENS;
			}
		} catch (Exception e) {
			log.error("預覽附件報錯。附件id:" + attachId.replaceAll("[\r\n]", ""));
			log.error(ExceptionUtils.getTrace(e));
		} finally {
			if (os != null) {
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					log.error(ExceptionUtils.getTrace(e));
				}
			}
		}
	}

 預覽效果如下,後面的下面沒有缺失數據  是我沒填

預覽效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章