使用Aspose.Words for Java完成复杂Word

 

1、 Controller  控制层

 @ApiOperation("打印送达回证")
    @ApiImplicitParam(value = "打印送达回证", paramType = "body", name = "param", dataType = "printSDHZ", required = true)
    @RequestMapping(value = "printsdhz", method = RequestMethod.POST)
    public void printsdhz(@RequestBody printSDHZ printSDHZ , HttpServletResponse response) throws IOException {
        String[] name = new String[]{
                "caseCause","sendOwner","sendaddress","senddocnum",
                "receivesignature","receivetime","receivecause","sendway",
                "remark","signer","sendperson",
        };
        Object[] value = new Object[]{
                printSDHZ.getCaseCause(),
                printSDHZ.getSendOwner(),
                printSDHZ.getSendaddress(),
                printSDHZ.getSenddocnum(),
                printSDHZ.getReceivesignature(),
                printSDHZ.getReceivetime(),
                printSDHZ.getReceivecause(),
                printSDHZ.getSendway(),
                printSDHZ.getRemark(),
                printSDHZ.getSigner(),
                printSDHZ.getSendperson(),
        };
//        String modelPath = ajzfConfig.print().printSDHZ;
        String modelPath = "D:\\sdhz.doc";
        PrintingMethod printingMethod=new PrintingMethod();

        printingMethod.printUtil(response, name, value, modelPath,"送达回证.doc");
    }

2、工具类

package cn.com.oceansoft.osc.ms.word;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author 
 * @Date: 2019/7/18 10:26
 */
public class PrintingMethod {

    public void printUtil(HttpServletResponse response, String[] name, Object[] value, String modelPath, String wordname) {
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream out = null;
        try {
            bufferedInputStream = new BufferedInputStream(new MergeDataSource().load(name, value, modelPath));
            //设置文件MIME类型
            response.setContentType(new MimetypesFileTypeMap().getContentType(modelPath));
            //设置Content-Disposition
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(wordname.getBytes("gb2312"), "ISO8859-1"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            out = new BufferedOutputStream(response.getOutputStream());
            int b;
            byte[] bytes = new byte[1024 * 1024];
            while ((b = bufferedInputStream.read(bytes, 0, bytes.length)) != -1) {
                out.write(bytes, 0, b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public void printUtil(HttpServletResponse response, String[] name, String[] value, String modelPath ,List<Map<String, Object>> dataList,String wordname) {
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream out = null;
        try {
            bufferedInputStream = new BufferedInputStream(new MergeDataSource().load(name, value, modelPath,dataList));
            //设置文件MIME类型
            response.setContentType(new MimetypesFileTypeMap().getContentType(modelPath));
            //设置Content-Disposition
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(wordname.getBytes("gb2312"), "ISO8859-1"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            out = new BufferedOutputStream(response.getOutputStream());
            int b;
            byte[] bytes = new byte[1024 * 1024];
            while ((b = bufferedInputStream.read(bytes, 0, bytes.length)) != -1) {
                out.write(bytes, 0, b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
package cn.com.oceansoft.osc.ms.word;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.License;
import com.aspose.words.MailMerge;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;


public class MergeDataSource extends AsposeLicense {

    private static License license = null;

    private boolean getLicense() {
        boolean result = true;
        try {
            if (license == null) {
                license = new License();
                license.setLicense(getLiceseIn());
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public ByteArrayInputStream load(String[] name, Object[] value, String modelPath) throws Exception {
        if (!getLicense()) {
            return null;
        }
        Document doc = new Document(modelPath);
        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.moveToMergeField("caseCause"); //变量名称
        builder.getFont().setName("Wingdings 2"); //字体
        builder.getFont().setSize(20);//字体大小
        builder.getFont().setItalic(true); //字体是斜体
//        builder.write("R");   //代表 方框里有对勾
        builder.write("*");    //代表 方框里无对勾


        //word里多个特殊符号
        builder.moveToMergeField("sendOwner");
        builder.getFont().setName("Wingdings 2");
        builder.getFont().setSize(20);
        builder.write("*");



        MailMerge merge = doc.getMailMerge();
        merge.execute(name, value);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        doc.save(bos, OfficeSaveFormat.W_DOCX);
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        return bis;
    }


  /**
     * 这个方法为word 里有循环的表格
     * @param name
     * @param value
     * @param modelPath
     * @param dataList
     * @return
     * @throws Exception
     */
    public ByteArrayInputStream load(String[] name, String[] value, String modelPath, List<Map<String, Object>> dataList) throws Exception {
        if (!getLicense()) {
            return null;
        }
        Document doc = new Document(modelPath);
        MailMerge merge = doc.getMailMerge();
        doc.getMailMerge().executeWithRegions(new MapMailMergeDataSource(dataList, "bcdList"));
        merge.execute(name, value);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        doc.save(bos, OfficeSaveFormat.W_DOCX);
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        return bis;
    }

}

4、word 里有循环表格的 Controller 与 工具类

package cn.com.oceansoft.osc.ms.word;

import com.aspose.words.IMailMergeDataSource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class MapMailMergeDataSource implements IMailMergeDataSource {

    private List<Map<String, Object>> dataList;

    private int index;
    /**
     * word模板中的«TableStart:tableName»«TableEnd:tableName»对应
     */

    private String tableName = null;

    /**
     * @param dataList  数据集
     * @param tableName 与模板中的Name对应
     */
    public MapMailMergeDataSource(List<Map<String, Object>> dataList, String tableName) {
        this.dataList = dataList;
        this.tableName = tableName;
        index = -1;
    }

    /**
     * @param data      单个数据集
     * @param tableName 与模板中的Name对应
     */
    public MapMailMergeDataSource(Map<String, Object> data, String tableName) {
        if (this.dataList == null) {
            this.dataList = new ArrayList<Map<String, Object>>();
            this.dataList.add(data);
        }
        this.tableName = tableName;
        index = -1;
    }

    /**
     * 获取结果集总数
     *
     * @return
     */
    private int getCount() {
        return this.dataList.size();
    }

    @Override
    public IMailMergeDataSource getChildDataSource(String arg0)
            throws Exception {
        return null;
    }

    @Override
    public String getTableName() throws Exception {
        return this.tableName;
    }

    /**
     * 实现接口
     * 获取当前index指向数据行的数据
     * 将数据存入args数组中即可
     *
     * @return ***返回false则不绑定数据***
     */
    @Override
    public boolean getValue(String key, Object[] args) throws Exception {
        if (index < 0 || index >= this.getCount()) {
            return false;
        }
        if (args != null && args.length > 0) {
            args[0] = this.dataList.get(index).get(key);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 实现接口
     * 判断是否还有下一条记录
     */
    @Override
    public boolean moveNext() throws Exception {
        index += 1;
        if (index >= this.getCount()) {
            return false;
        }
        return true;
    }
}
 @ApiOperation("证据发还通知书")
    @ApiImplicitParam(value = "证据发还通知书", paramType = "body", name = "param", dataType = "JSONObject", required = true)
    @RequestMapping(value = "zjfh", method = RequestMethod.POST)
    public void printZjfh(@RequestBody JSONObject jsonObject, HttpServletResponse response) throws IOException {
        try {
            String[] name = new String[]{
                    "name",
                    "idnumber",
                    "address",
                    "workunit",
                    "homeaddress",
                    "legalProxy",
                    "startTime",
                    "conditions",
                    "illegalPlace",
                    "bcr",
                    "endTime",
                    "dsr",
                    "dsrtiem",
            };

            String[] value = new String[]{
                    jsonObject.getString("name"),
                    jsonObject.getString("idnumber"),
                    jsonObject.getString("address"),
                    jsonObject.getString("workunit"),
                    jsonObject.getString("homeaddress"),
                    jsonObject.getString("legalProxy"),
                    jsonObject.getString("startTime"),
                    jsonObject.getString("conditions"),
                    jsonObject.getString("illegalPlace"),
                    jsonObject.getString("bcr"),
                    jsonObject.getString("endTime"),
                    jsonObject.getString("dsr"),
                    jsonObject.getString("dsrtiem"),
            };
            List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
            JSONArray bcdList = jsonObject.getJSONArray("bcdList");
            if(bcdList!=null){
                int number = 1;
                for (int i = 0; i < bcdList.size(); i++) {
                    Map<String, Object> record = new HashMap<String, Object>(10);
                    record.put("xuhao", number);
                    number++;
                    record.put("name", bcdList.getJSONObject(i).get("name"));
                    record.put("type", bcdList.getJSONObject(i).get("type"));
                    record.put("unit", bcdList.getJSONObject(i).get("unit"));
                    record.put("num", bcdList.getJSONObject(i).get("num"));
                    record.put("remark", bcdList.getJSONObject(i).get("remark"));
                    dataList.add(record);
                }
            }else {
                Map<String, Object> record = new HashMap<String, Object>(10);
                record.put("xuhao", "");
                record.put("name", "");
                record.put("type", "");
                record.put("unit", "");
                record.put("num", "");
                record.put("remark", "");
                dataList.add(record);
            }
            String modelPath = ajzfConfig.print().printZJFH;
            PrintingMethod printingMethod = new PrintingMethod();

            printingMethod.printUtil(response, name, value, modelPath, dataList, "证据发还.doc");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

 字符对应的特殊符号

更多  https://wenku.baidu.com/view/81b41244336c1eb91a375dcb.html

参考

https://www.iteye.com/blog/183615215-qq-com-1858216

https://183615215-qq-com.iteye.com/blog/1858216

http://www.zuidaima.com/code/file/2692679231783936.htm?dir=/AsposeWord/src/com/demo/TestWord.java 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值