shichongfu
2023-06-15 d873c581e95fdabe4f1a32d95e283a1e1c20c980
文档处理
已修改1个文件
200 ■■■■■ 文件已修改
src/main/java/com/product/file/util/AsposeUtil.java 200 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/product/file/util/AsposeUtil.java
@@ -9,6 +9,7 @@
import java.text.DecimalFormat;
import com.aspose.cells.Cells;
import com.aspose.cells.HtmlSaveOptions;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;
@@ -16,7 +17,12 @@
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.ImportFormatMode;
import com.aspose.words.NodeCollection;
import com.aspose.words.NodeType;
import com.aspose.words.Paragraph;
import com.aspose.words.SaveFormat;
import com.aspose.words.Section;
import com.aspose.words.SectionStart;
import com.product.core.exception.BaseException;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.file.config.FileCode;
@@ -24,10 +30,8 @@
public class AsposeUtil {
    //是否初始了license
    private static boolean isInitLicense = false;
    /**
     * 获取license
     *
     * @return
     */
    public static boolean getLicense(int type) throws BaseException {
@@ -65,8 +69,8 @@
        }
        return result;
    }
    /**
     *
     * @param officePath
     * @param OutPutPath
     * @throws BaseException
@@ -79,8 +83,8 @@
        FileOutputStream fileOS = null;
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Workbook wb = new Workbook(officePath);// 原始excel路径
            fileOS = new FileOutputStream(OutPutPath);
@@ -101,26 +105,30 @@
            }
        }
    }
    public static void Excel2Html(String officePath, String OutPutPath) throws BaseException {
    /**
     *
     * @param officePath
     * @param OutPutPath
     * @throws BaseException
     */
    public static void xls2xlsx(String officePath,String OutPutPath,String officeType)throws BaseException {
        // 验证License
        if (!getLicense(1)) {
            return;
        }
        if("xlsx".equals(officeType)) {
            FileUtil.copyFile(new File(officePath), OutPutPath);
            return;
        }
        FileOutputStream fileOS = null;
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Workbook wb = new Workbook(officePath);// 原始excel路径
            WorksheetCollection sheets = wb.getWorksheets();
            System.out.println("sheet个数:" + sheets.getCount());
            for (int i = 0; i < sheets.getCount(); i++) {
                setAutoWithHeight(sheets.get(i));
            }
            fileOS = new FileOutputStream(OutPutPath);
            wb.save(fileOS, SaveFormat.HTML);
            wb.save(fileOS, com.aspose.cells.SaveFormat.XLSX);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
        } finally {
@@ -134,27 +142,62 @@
            }
        }
    }
    public static void Excel2Html(String officePath,String OutPutPath)throws BaseException {
        // 验证License
        if (!getLicense(1)) {
            return;
        }
        FileOutputStream fileOS=null;
        try {
            File file = new File(OutPutPath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Workbook wb = new Workbook(officePath);// 原始excel路径
            WorksheetCollection sheets=wb.getWorksheets();
            System.out.println("sheet个数:"+sheets.getCount());
            for(int i=0;i<sheets.getCount();i++) {
                //setAutoWithHeight(sheets.get(i));
            }
//            HtmlSaveOptions options = new HtmlSaveOptions();
//            options.setPresentationPreference(true);
            fileOS = new FileOutputStream(OutPutPath);
            wb.save(fileOS, com.aspose.cells.SaveFormat.HTML);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(fileOS!=null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                }catch(IOException e) {
                    throw new BaseException(e);
                }
            }
        }
    }
    /**
     * 设置单元格的自动适宽、高
     *
     * @param sheet
     * @throws Exception
     */
    public static void setAutoWithHeight(Worksheet sheet) throws Exception {
    public static void setAutoWithHeight(Worksheet sheet)throws Exception
    {
        Cells cells = sheet.getCells();
        int columnCount = cells.getMaxColumn();  //获取表页的最大列数
        int rowCount = cells.getMaxRow();        //获取表页的最大行数
        if (columnCount < 0 || rowCount < 0) return;
        for (int col = 0; col < columnCount; col++) {
        for (int col = 0; col < columnCount; col++)
        {
            sheet.autoFitColumn(col, 0, rowCount);
        }
        for (int row = 0; row < rowCount; row++) {
        for (int row = 0; row < rowCount; row++)
        {
            sheet.autoFitRow(row, 0, columnCount);
        }
    }
    /**
     *
     * @param officePath
     * @param OutPutPath
     * @throws BaseException
@@ -167,8 +210,8 @@
        FileOutputStream fileOS = null;
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Document doc = new Document(officePath);// 原始word路径
            fileOS = new FileOutputStream(OutPutPath);
@@ -186,8 +229,8 @@
            }
        }
    }
    /**
     *
     * @param officePath
     * @param OutPutPath
     * @throws BaseException
@@ -200,8 +243,8 @@
        FileOutputStream fileOS = null;
        try {
            File PathFile = new File(OutPutPath);
            if (!PathFile.exists()) {
                PathFile.mkdirs();
            if (!PathFile.getParentFile().exists()) {
                PathFile.getParentFile().mkdirs();
            }
            InputStream slides = new FileInputStream(officePath);// 原始ppt路径
            Presentation pres = new Presentation(slides);
@@ -220,17 +263,15 @@
            }
        }
    }
    /**
     * 文档转换
     *
     * @param officePath
     * @param outFile
     * @return
     * @throws BaseException
     */
    public static String OfficeToPdf(String officePath, String outFile, String officeType) throws BaseException {
        officeType=officeType.toLowerCase();
        SpringMVCContextHolder.getSystemLogger().info("The file of office type:" + officePath);
        if ("pdf".equals(officeType)) {
            return outFile;
@@ -242,7 +283,8 @@
                Word2Pdf(officePath, outFile);
            } else if (officeType.equals("xls") || officeType.equals("xlsx")) {
//                Excel2Pdf(officePath,outFile);
                Excel2Html(officePath, outFile);
//                Excel2Html(officePath,outFile);
                xls2xlsx(officePath,outFile,officeType);
            } else if (officeType.equals("ppt") || officeType.equals("pptx")) {
                PPT2Pdf(officePath, outFile);
            } else {
@@ -253,10 +295,8 @@
        }
        return outFile;
    }
    /**
     * 文档转换
     *
     * @param officePath
     * @return
     */
@@ -267,37 +307,21 @@
        int lastNameIndex = split[0].lastIndexOf("/");
        String officeType = split[0].substring(lastIndex + 1);
        String officeName = split[0].substring(lastNameIndex + 1, lastIndex) + ".pdf";
        String officeName = split[0].substring(lastNameIndex+1,lastIndex);
        String OutPutPath = split[0].substring(0, lastNameIndex + 1) + "office/";
        System.out.println("输出目录:" + OutPutPath);
        File file = new File(split[0]);
        File pdfFile = new File(OutPutPath + officeName);
        //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
        if (pdfFile.exists()) {
            return OutPutPath + officeName;
        }
        if (file.exists()) {
            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);
            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);
            String MB = df.format(megabytes);
            Double Size = Double.parseDouble(MB);
            if (Size > 10) {
                return Size + "MB";
            }
            //"doc", "docx", "xls","xlsx", "ppt", "pptx"
            try {
                if (officeType.equals("doc") || officeType.equals("docx")) {
                    Word2Pdf(split[0], OutPutPath + "/" + officeName);
                    Word2Pdf(split[0],OutPutPath+"/"+officeName+".pdf");
                } else if (officeType.equals("xls") || officeType.equals("xlsx")) {
                    Excel2Pdf(split[0], OutPutPath + "/" + officeName);
//                    Excel2Html(split[0],OutPutPath+"/"+officeName+".html");
                    xls2xlsx(split[0],OutPutPath+"/"+officeName+".xlsx",officeType);
                } else if (officeType.equals("ppt") || officeType.equals("pptx")) {
                    PPT2Pdf(split[0], OutPutPath + "/" + officeName);
                    PPT2Pdf(split[0],OutPutPath+"/"+officeName+".pdf");
                } else {
                    System.out.println("无法识别该文件!");
                    return "Error";
@@ -310,10 +334,8 @@
        }
        return OutPutPath + officeName;
    }
    /**
     * word文档的合并
     *
     * @param targetWordFile
     * @param sourceWordFile
     * @return
@@ -324,15 +346,8 @@
        File source = new File(sourceWordFile);
        return mergeWord(target, source);
    }
    public static void main(String args[]) {
        String file = "E:/work/沄崃/FE6.6产品报价工具-新 - 副本.xlsx";
        AsposeUtil.OfficeToPdf(file);
    }
    /**
     * word文档的合并
     *
     * @param targetWordFile
     * @param sourceWordFile
     * @return
@@ -361,10 +376,22 @@
            sin = new FileInputStream(source);
            Document targetDoc = new Document(tin);
            Document sourceDoc = new Document(sin);
            docBlankProcess(targetDoc);
            targetDoc.appendDocument(sourceDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
//            for(Section sect : targetDoc.getSections())
//            {
//                if (sect.getBody().getParagraphs().getCount() == 0) {
//                    sect.remove();
//                }
//            }
            File dir = new File(temp);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            if(temp_target.exists()) {
                temp_target.delete();
            }
            if (temp_target.createNewFile()) {
                out = new FileOutputStream(temp_target);
@@ -372,7 +399,8 @@
            }
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_MERGE_FALL, e);
        } finally {
        }
        finally{
            try {
                if (tin != null) {
                    tin.close();
@@ -390,4 +418,50 @@
        }
        return temp_target;
    }
    public static void docBlankProcess(Document targetDoc) {
        NodeCollection nodes=targetDoc.getChildNodes(NodeType.PARAGRAPH, true);
        System.out.println(nodes.getCount());
        for(Paragraph para :(Iterable<Paragraph>) nodes) {
            String text=para.getText();
            if("\r".equals(text)) {
                System.out.println("rrrrrrrrrrrr");
            }else if("\f".equals(text)) {
                System.out.println("ffffffffffff");
            }else {
                System.out.println(text);
            }
            if ("\r".equals(text)
                    //|| "\f".equals(text)
                    ) {
                para.remove();
            }
        }
    }
    public static void docProcess(Document targetDoc) {
        NodeCollection nodes=targetDoc.getChildNodes();
        for(Paragraph para :(Iterable<Paragraph>) nodes) {
            String text=para.getText();
            if("\r".equals(text)) {
                System.out.println("rrrrrrrrrrrr");
            }else if("\f".equals(text)) {
                System.out.println("ffffffffffff");
            }else {
                System.out.println(text);
            }
            if ("\r".equals(text)
                    //|| "\f".equals(text)
                    ) {
                para.remove();
            }
        }
    }
    public static void main(String args[]) {
        String file="E:/工作内容.xlsx";
//        String file="E:/爆破母线.xls";
//        String file="E:/采集提取日志表结构.xlsx";
//        String file="E:/FE信息系统国产化解决方案V1.0.docx";
        AsposeUtil.OfficeToPdf(file);
//        AsposeUtil.mergeWord("E:\\QQ\\住房担保置换公司.docx","E:\\QQ\\住房担保置换公司2.docx");
    }
}