欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java读取xslx内容,内容转换成docx和pdf,包括图片

程序员文章站 2024-01-18 23:02:34
...

WPS创建或打开的文件有可能解析有误
student.xslx文件如下:
java读取xslx内容,内容转换成docx和pdf,包括图片
student.docx文件内容如下:
java读取xslx内容,内容转换成docx和pdf,包括图片
程序运行结果如下:
java读取xslx内容,内容转换成docx和pdf,包括图片
java读取xslx内容,内容转换成docx和pdf,包括图片

源码示例:

java读取xslx内容,内容转换成docx和pdf,包括图片
pom.xml

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>core</artifactId>
        <version>3.3.3</version>
    </dependency>
    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>javase</artifactId>
        <version>3.3.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sf.barcode4j/barcode4j -->
    <dependency>
        <groupId>net.sf.barcode4j</groupId>
        <artifactId>barcode4j</artifactId>
        <version>2.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.avalon.framework/avalon-framework-api -->
    <dependency>
        <groupId>org.apache.avalon.framework</groupId>
        <artifactId>avalon-framework-api</artifactId>
        <version>4.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.14</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>ooxml-schemas</artifactId>
        <version>1.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>3.14</version>
    </dependency>
    <dependency>
        <groupId>org.apache.xmlbeans</groupId>
        <artifactId>xmlbeans</artifactId>
        <version>2.6.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-examples</artifactId>
        <version>3.14</version>
    </dependency>
    <dependency>
        <groupId>fr.opensagres.xdocreport</groupId>
        <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
        <version>1.0.6</version>
    </dependency>
</dependencies>
package com.torey.docxtext2;

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName:DocxHelp
 * @Description:
 * @author: Torey
 */
public class DocxHelp {

    public static Pattern pattern = Pattern.compile("\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
    /**
     *
     * @param templatePath 文件模板路径
     * @param newFilePath 生成新的文件路径
     * @param params 文字类key-value
     * @param picParams 图片类key-value
     */
    public static void writeDocx(String newFilePath,String templatePath,Map<String,Object> params,Map<String,String> picParams) throws Exception {
        XWPFDocument docx = openDocx(templatePath);
        List<IBodyElement> ibes = docx.getBodyElements();
        for (IBodyElement ibe : ibes) {
            if (ibe.getElementType()==BodyElementType.TABLE) {
                replaceTable(ibe,params,docx);
            }
            if(ibe.getElementType()==BodyElementType.PARAGRAPH){
                XWPFParagraph para = (XWPFParagraph) ibe;
                List<XWPFRun> res = para.getRuns();
                String code=picParams.get("{barcode}");
                System.out.println("code="+code);
                for (XWPFRun re : res) {
                    String runtext = re.text();
                    Matcher matcher = matcher(runtext);
                    if (matcher.find()) {
                        for (String pickey : picParams.keySet()) {
                            if (matcher.group().equals(pickey)) {
                               // re.setText(picParams.get(pickey) + "", 0);// null会出错,空字符串行
                               // re.setText(picParams.get(pickey)+"",0);
                                re.setText("",0);
                              //  System.out.println(re.getText(0));
                                // re.setText("s");
                                int format = 1;
                                if (format != 0) {
                                    if (code.endsWith(".emf"))
                                        format = XWPFDocument.PICTURE_TYPE_EMF;
                                    else if (code.endsWith(".wmf"))
                                        format = XWPFDocument.PICTURE_TYPE_WMF;
                                    else if (code.endsWith(".pict"))
                                        format = XWPFDocument.PICTURE_TYPE_PICT;
                                    else if (code.endsWith(".jpeg") || code.endsWith(".jpg"))
                                        format = XWPFDocument.PICTURE_TYPE_JPEG;
                                    else if (code.endsWith(".png"))
                                        format = XWPFDocument.PICTURE_TYPE_PNG;
                                    else if (code.endsWith(".dib"))
                                        format = XWPFDocument.PICTURE_TYPE_DIB;
                                    else if (code.endsWith(".gif"))
                                        format = XWPFDocument.PICTURE_TYPE_GIF;
                                    else if (code.endsWith(".tiff"))
                                        format = XWPFDocument.PICTURE_TYPE_TIFF;
                                    else if (code.endsWith(".eps"))
                                        format = XWPFDocument.PICTURE_TYPE_EPS;
                                    else if (code.endsWith(".bmp"))
                                        format = XWPFDocument.PICTURE_TYPE_BMP;
                                    else if (code.endsWith(".wpg"))
                                        format = XWPFDocument.PICTURE_TYPE_WPG;
                                    else
                                        System.err.println("Unsupported picture: " + code
                                                + ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");

                                    re.addPicture(new FileInputStream(code), format, "",
                                            Units.toEMU(200), Units.toEMU(50));
                                }

                            }
                        }
                    }
                }
            }
        }
        writeDocx(docx,new FileOutputStream(newFilePath));//输出
    }


    public static XWPFDocument openDocx(String url) {
        InputStream in = null;
        try {
            in = new FileInputStream(url);
            XWPFDocument doc = new XWPFDocument(in);
            return doc;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void writeDocx(XWPFDocument outDoc, OutputStream out) {
        try {
            outDoc.write(out);
            out.flush();
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Matcher matcher(String str) {
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }


    /**
     * 替换表格内占位符
     * @param para 表格对象
     * @param params 文字替换map
     * @param indoc
     * @throws Exception
     */
    public static void replaceTable(IBodyElement para ,Map<String, Object> params, XWPFDocument indoc)
            throws Exception {
        Matcher matcher;
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        table = (XWPFTable) para;
        rows = table.getRows();
        for (XWPFTableRow row : rows) {
            cells = row.getTableCells();
            int cellsize = cells.size();
            int cellcount = 0;
            for(cellcount = 0; cellcount<cellsize;cellcount++){
                XWPFTableCell cell = cells.get(cellcount);
                String runtext = "";
                List<XWPFParagraph> ps = cell.getParagraphs();
                String text = cell.getText();
                System.out.println("text="+text);
                matcher = matcher(runtext);
                for (XWPFParagraph p : ps) {
                    for(XWPFRun run : p.getRuns()){
                        runtext = run.text();
                        System.out.println("====111");
                        System.out.println(runtext);
                        matcher = matcher(runtext);
                        if (matcher.find()) {
                            if (params != null) {
                                for (String pickey : params.keySet()) {
                                    if (matcher.group().equals(pickey)) {
                                        run.setText(params.get(pickey)+"",0);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

package com.torey.docxtext2;

/**
 * @ClassName:Student
 * @Description:
 * @author: Torey
 */
public class Student {
    private String name;
    private String set;
    private String barcode;
    private String barcodeImgPath;

    public String getBarcodeImgPath() {
        return barcodeImgPath;
    }

    public void setBarcodeImgPath(String barcodeImgPath) {
        this.barcodeImgPath = barcodeImgPath;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSet() {
        return set;
    }

    public void setSet(String set) {
        this.set = set;
    }

    public String getBarcode() {
        return barcode;
    }

    public void setBarcode(String barcode) {
        this.barcode = barcode;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", set='" + set + '\'' +
                ", barcode='" + barcode + '\'' +
                '}';
    }
}

package com.torey.docxtext2;

import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
import fr.opensagres.xdocreport.itext.extension.font.ITextFontRegistry;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.krysalis.barcode4j.impl.code39.Code39Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName:Start
 * @Description:
 * @author: Torey
 */
public class MainSta {
    /**
     * 读取student.xslx里面的数据,
     * 根据预设的student.docx模板,
     * 生成学生具体的信息文档,
     * 最后转化为pdf文档。
     * @param args
     */
    public static void main(String[] args){
        try {
            startRun();
            System.out.println("程序运行完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void startRun() throws Exception{
        String url = Thread.currentThread().getContextClassLoader().getResource("docx").getPath();
//            //student.xlsx中的内容转换为Student
        String studentXlsxPath=url+"/student.xlsx";
        Student student = getStudent(studentXlsxPath);
        String genUrl=url+"/barcode.png";
            //生成二维码文件
            generateFile(student.getBarcode(),genUrl);
            //将二维码文件路径赋值给student
            student.setBarcodeImgPath(genUrl);
        String templateUrl=url+"/student.docx";
        String newFileUrl=url+"/newStudent.docx";
        //将数据写到newStudent.docx文件中
        setStudentDocx(student,newFileUrl,templateUrl );
        String newPdfUrl=url+"/student.pdf";
        //将newStudent.docx文件转换为student.pdf
        docxToPdf(newFileUrl,newPdfUrl);
        System.out.println("student.pdf文件地址:"+newPdfUrl);
        System.out.println("newStudent.docx文件地址:"+newFileUrl);
    }
    /**
     * 将docx文件转换为pdf文件
     * @param docxPath docx目标文件
     * @param newPdfPath pdf新文件地址
     * @throws Exception
     */
    private static void docxToPdf(String docxPath,String newPdfPath ) throws Exception {
    XWPFDocument doc = new XWPFDocument(new FileInputStream(docxPath));
    PdfOptions options = PdfOptions.create();
    options.fontProvider(new IFontProvider() {
        //设置中文字体
        @Override
        public Font getFont(String familyName, String encoding, float size, int style, Color color) {
            try{
                BaseFont bfChinese = BaseFont.createFont(
                        "C:\\Windows\\Fonts\\STSONG.TTF",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
                Font fontChinese = new Font(bfChinese, size, style, color);
                if (null!= familyName) {
                    fontChinese.setFamily(familyName);
                    return fontChinese;
                }
            }catch (Exception ex){
                ex.printStackTrace();
                return ITextFontRegistry.getRegistry().getFont(familyName,encoding,size,style,color);
            }
            return null;
        }
    });
    PdfConverter.getInstance().convert(doc,new FileOutputStream(newPdfPath),options);
}
    /**
     * 将student.xlsx中的内容转换为Student
     * @param path 文件路径
     * @return
     * @throws Exception
     */
    private static Student getStudent(String path) throws Exception {
        Student student = new Student();
        InputStream ExcelFileToRead = new FileInputStream(path);
        XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
        XSSFSheet sheet = wb.getSheetAt(0);
        XSSFRow row1 = sheet.getRow(0);
        student.setName(row1.getCell(0).getStringCellValue());
        student.setSet(row1.getCell(1).getStringCellValue());
        student.setBarcode(row1.getCell(2).getStringCellValue());
        System.out.println("studen的值为:"+student);
        return student;
    }

    /**
     * 将数据写入到student.docx文件中
     * @param student 数据
     * @param newFileUrl 产生的新文件地址
     * @param templateUrl 模板文件地址
     * @throws Exception
     */
    private static void setStudentDocx(Student student, String newFileUrl, String templateUrl) throws Exception {
        Map<String,Object> params=new HashMap<>();
        params.put("{name}",student.getName());
        params.put("{sex}",student.getSet());
        Map<String,String> picParams=new HashMap<>();
        picParams.put("{barcode}",student.getBarcodeImgPath());
        DocxHelp.writeDocx(newFileUrl,templateUrl,params,picParams);
    }

    /**
     * 生成二维码文件
     * @param msg
     * @param path
     */
    private static void generateFile(String msg, String path) {
        File file = new File(path);
        try{
            //Code39 EAN13 都是一维条形码的不同标注
            Code39Bean code39Bean = new Code39Bean();
            //EAN13Bean ean13Bean = new EAN13Bean();
            //dpi精度 像素精度
            final int dpi=150;
            //module宽度
            //bean.setModuleWidth(0.2)
            final double width=UnitConv.in2mm(2.0f/dpi);
            code39Bean.setWideFactor(3);
            code39Bean.setModuleWidth(width);
            code39Bean.doQuietZone(false);

            String formar="image/png";
            //输出到流
            BitmapCanvasProvider canvasProvider = new BitmapCanvasProvider(new FileOutputStream(file), formar, dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
            //生成条形码
            code39Bean.generateBarcode(canvasProvider,msg);
            //结束绘制
            canvasProvider.finish();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }


}