POI操作word与excel

文章目录

一、poi生成word文档

1.构建文档数据

2.生成word文档

3.图片信息处理

二、poi实现word转pdf

三、poi实现excel转pdf


一、poi生成word文档

1.构建文档数据

//数据信息
Map<String, Object> map = new HashMap<>();
map.put("gradeReportName", gradeReportInfo.getGradeReportName());
map.put("createTimeStr", DateUtil.toString(gradeReportInfo.getCreateTime()));
//图片信息
List<String> impPathList = new ArrayList<>();
boolean buildFlag = getWord('文件路径', '模板名称', 'word文件名称', map,impPathList);

2.生成word文档

public static boolean getWord(String uploadFilePath, String templateName, String wordName, Map<String, Object> dataMap,List<String> imgPathList) {
    	boolean buildFlag = true;
    	//生成的word文档路径
    	String docxPath = uploadFilePath + File.separator + wordName;
    	//加载模板文件
    	String templateOutPath = uploadFilePath + File.separator + templateName;
    	//构建图片信息
    	if (CollectionUtil.isNotEmpty(imgPathList)) {
    		dataMap.put("imgList", getImgList(imgPathList));
		}
    	FileOutputStream in = null;
    	XWPFTemplate template = null;
    	try {
			template = XWPFTemplate.compile(templateOutPath).render(
				new HashMap<String, Object>(){{
					for (Map.Entry<String, Object> map : dataMap.entrySet()) {
						put(map.getKey(), map.getValue());
					}
				}}
			);
			in = new FileOutputStream(docxPath);
			template.writeAndClose(in);
    	} catch (Exception e) {
			log.error("poi生成word文档异常",e);
			buildFlag = false;
		} finally {
			FileUtil.closeStream(in);
			try {
				template.close();
			} catch (IOException e) {
				log.error("XWPFTemplate对象关闭异常",e);
			}
		}
		return buildFlag;
    }

3.图片信息处理

public static List<Map<String, Object>> getImgList(List<String> imgPathList){
    	List<Map<String, Object>> imgMapList = new ArrayList<>();
		Map<String, Object> dataMap = null;
		List<Map<String, Object>> picList = new ArrayList<>();
		Map<String, Object> imageMap = null;
		//获取网络情况图片信息
	    if (CollectionUtil.isNotEmpty(imgPathList)) {
	    	dataMap = new HashMap<>();
	    	for (String filePath : imgPathList) {
	    		imageMap = new HashMap<>();
	    		imageMap.put("image", Pictures.ofLocal(filePath).fitSize().create());
	    		picList.add(imageMap);
			}
	    	dataMap.put("images", picList);
	    	imgMapList.add(dataMap);
	    }
	    return imgMapList;
}

二、poi实现word转pdf

public static boolean wordCovertPdf(String uploadFilePath,String destFileDir,String wordName,String pdfName,boolean isCreateFont) {
		log.info("start word covert pdf-------");
		boolean covertFlag = true;
		InputStream in = null;
		OutputStream outPDF = null;
		try {
	        in = Files.newInputStream(Paths.get(destFileDir + File.separator + wordName));
	        XWPFDocument document = new XWPFDocument(in);
	        //设置字体
	        if (isCreateFont) {
	        	createFile(uploadFilePath, "arialuni.ttf", false, "classpath*:template/");
			}
	        PdfOptions pdfOptions = PdfOptions.create();
	        pdfOptions.fontProvider(new IFontProvider() {
				String tempPath = uploadFilePath;
				public Font getFont(String familyName, String encoding, float size, int style, Color color) {
					try {
						if (!tempPath.endsWith("/")) {
							tempPath += "/";
						}
						BaseFont bfChinese = BaseFont.createFont(tempPath + File.separator + "arialuni.ttf", BaseFont.IDENTITY_H,
								BaseFont.EMBEDDED);
						Font fontChinese = new Font(bfChinese, size, style, color);
						if (familyName != null) {
							fontChinese.setFamily(familyName);
						}
						return fontChinese;
					} catch (Exception e) {
						log.error("getFont-error", e);
						return null;
					}
				}
			});
	        outPDF = Files.newOutputStream(Paths.get(destFileDir + File.separator + pdfName));
			PdfConverter.getInstance().convert(document, outPDF, pdfOptions);
	    } catch (Exception e) {
	    	log.error("word 转 pdf 异常");
		    log.error(e.getMessage(),e);
		    covertFlag = false;
	    } finally {
			FileUtil.closeStream(in);
			FileUtil.closeStream(outPDF);
		}
		log.info("end word covert pdf-------");
		return covertFlag;
	}

三、poi实现excel转pdf

public static boolean excelCovertPdf(String uploadFilePath,String destFileDir,String excelName, String pdfName,boolean isCreateFont) {
		log.info("start excel covert pdf-------");
		boolean covertFlag = true;
        PdfFont pdfFont = null;
        InputStream in = null;
        try (PdfDocument pdf = new PdfDocument(new PdfWriter(new FileOutputStream(destFileDir + File.separator + pdfName)));
                Document document = new Document(pdf, PageSize.A2.rotate());) 
        {
        	//设置字体
        	if (isCreateFont) {
        		createFile(uploadFilePath, "arialuni.ttf", true, "classpath*:template/");
			}
        	pdfFont = PdfFontFactory.createFont(uploadFilePath + File.separator + "arialuni.ttf");
            String type = "xls".equals(getSuffix(destFileDir + File.separator + excelName).trim()) ? "org.apache.poi.hssf.usermodel.HSSFWorkbook"
                    : "org.apache.poi.xssf.usermodel.XSSFWorkbook";
            // 文件输入流读取文件
            in = new FileInputStream(destFileDir + File.separator + excelName);
            // 反射创建workbook
            Class workbookClass = Class.forName(type);
            org.apache.poi.ss.usermodel.Workbook workbook = (org.apache.poi.ss.usermodel.Workbook) workbookClass
                    .getConstructor(InputStream.class).newInstance(in);
            Sheet sheet = workbook.getSheetAt(0);
            int row = sheet.getPhysicalNumberOfRows();
            int maxColumn=0;
            for (int q = sheet.getFirstRowNum(); q <=row+1; q++) {
                Row r =  sheet.getRow(q);
                if(r==null){
                    continue;
                }
                org.apache.poi.ss.usermodel.Cell firstCell = sheet.getRow(q).getCell(0);
                if(firstCell==null){
                    continue;
                }
                int currentRowMaxColumn = sheet.getRow(q).getLastCellNum();
                org.apache.poi.ss.usermodel.Cell cell = sheet.getRow(q).getCell(currentRowMaxColumn-1);
                if(cell==null){
                    continue;
                }else{
                    maxColumn = maxColumn>currentRowMaxColumn?maxColumn:currentRowMaxColumn;
                }
            }
            int column = maxColumn;
            Table table = new Table(column);
            String str = null;
            boolean addHeadFlag = false;
            for (int i = sheet.getFirstRowNum(); i <= row+1;i++) {
                Row r =  sheet.getRow(i);
                if(r==null){
                    continue;
                }
                for (int j = 0; j < column; j++) {
                    // 获取excel单元格
                    org.apache.poi.ss.usermodel.Cell cell = sheet.getRow(i).getCell(j);
                    if (cell!=null && cell.getCellType() == CellType.NUMERIC) {
                        str = cell.getNumericCellValue()+"";
                    }else if(cell!=null ){
                        str = cell.getStringCellValue();
                    }else{
                        str = null;
                    }
                    if(cell==null && j==0){
                        continue;
                    }else if(cell==null){
                        Cell cells = new Cell().setFont(pdfFont).add(new Paragraph(""));
                        table.addCell(cells);
                    }else if(str!=null && str.contains("报表") && (i==sheet.getFirstRowNum() || i==sheet.getFirstRowNum()+1) && addHeadFlag ){
                        Cell cells = new Cell().setFont(pdfFont).add(new Paragraph(""));
                        table.addCell(cells);
                    }else{
                        if (cell.getCellType() == CellType.NUMERIC) {
                            str = (int) cell.getNumericCellValue() + "";
                        } else {
                            str = cell.getStringCellValue();
                        }
                        Cell cells = new Cell().setFont(pdfFont).add(new Paragraph(str));
                        cells.setFontSize(14);//设置字体大小
                        table.addCell(cells);
                        addHeadFlag = true;
                    }
                }
            }
            document.add(table);
        } catch (Exception e) {
        	log.error("excel 转 pdf 异常");
            log.error(e.getMessage(),e);
            covertFlag = false;
        } finally {
			FileUtil.closeStream(in);
		}
        log.info("end excel covert pdf-------");
        return covertFlag;
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值