根据模板导出数据

    /**
     * 下载 导入错误信息表
     *
     * @param response
     * @param data
     * @throws Exception
     */
    public void exportPublicity (HttpServletResponse response, ApiResponse <?> data) {
        List <GysExcelErrorVo> list=
               "将要导出的数据";
        String base64=
                "我这里将模板转成base64了";
        File file1=base64ToFile ( base64 );
        InputStream is=null;
        XSSFWorkbook workbook=null;
        XSSFSheet sheet=null;
        try {
            is=new FileInputStream ( file1 );// 将excel文件转为输入流
            workbook=new XSSFWorkbook ( is );// 创建个workbook,
            // 获取第一个sheet
            sheet=workbook.getSheetAt ( 0 );
        } catch (Exception e1) {
            e1.printStackTrace ( );
        }
        if (sheet != null) {
            try {
                if (! CollectionUtils.isEmpty ( list )) {
                    // 写数据
                    FileOutputStream fos=new FileOutputStream ( file1 );
                    XSSFRow row=sheet.getRow ( 1 );
                    if (row == null) {
                        row=sheet.createRow ( 2 );
                    }
                    XSSFCell cell=row.getCell ( 0 );
                    if (cell == null) {
                        cell=row.createCell ( 0 );
                    }
                    for (int m=0; m < list.size ( ); m++) {
                        GysExcelErrorVo gysPrpLflehelperagent=list.get ( m );
                        row=sheet.createRow ( m + 1 );
                        List <Map> filedsInfo=getFiledsInfo ( gysPrpLflehelperagent );
                        for (int i=0; i < filedsInfo.size ( ); i++) {

                            Map map=filedsInfo.get ( i );
                            String value=String.valueOf ( map.get ( "value" ) );
                            String name=String.valueOf ( map.get ( "name" ) );
                            cell=row.createCell ( i );
                            cell.setCellValue ( value );
                        }
                    }
                    if (workbook != null) {
                        workbook.write ( fos );
                    }
                    fos.flush ( );
                    fos.close ( );
                }
                // 下载
                InputStream fis=new BufferedInputStream ( new FileInputStream ( file1 ) );
                byte[] buffer=new byte[fis.available ( )];
                fis.read ( buffer );
                fis.close ( );
                response.reset ( );
//                response.setContentType("text/html;charset=UTF-8");
                response.setContentType ( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" );
                response.setHeader ( "Content-Disposition", "attachment;filename=" + URLEncoder.encode ( "temp.xlsx", "utf-8" ) );
                response.setHeader ( "Set-Cookie", "cookiename=cookievalue; path=/; Domain=domainvaule; Max-age=seconds; HttpOnly" );
                OutputStream toClient=new BufferedOutputStream ( response.getOutputStream ( ) );
                toClient.write ( buffer );
                toClient.flush ( );
            } catch (Exception e) {
                throw new BusinessException ( "下载模板失败:" + e.getMessage ( ) );
            } finally {
                try {
                    if (null != is) {
                        is.close ( );
                    }
                } catch (Exception e) {
                    e.printStackTrace ( );
                }
            }
        }
    }


    /**
     * 获取属性类型(type),属性名(name),属性值(value)的map组成的list
     */
    private List <Map> getFiledsInfo (Object o) {
        Field[] fields=o.getClass ( ).getDeclaredFields ( );
        String[] fieldNames=new String[fields.length];
        List <Map> list=new ArrayList ( );
        Map infoMap;
        for (int i=0; i < fields.length; i++) {
            infoMap=new HashMap ( );
            infoMap.put ( "type", fields[i].getType ( ).toString ( ) );
            infoMap.put ( "name", fields[i].getName ( ) );
            Object value=getFieldValueByName ( fields[i].getName ( ), o );
            if (value == null || "null".equals ( value )) {
                value="";
            }
            infoMap.put ( "value", value );
            list.add ( infoMap );
        }
        return list;
    }

    /**
     * 根据属性名获取属性值
     *
     * @param fieldName 属性名称
     * @param o         对象
     * @return
     */
    private static Object getFieldValueByName (String fieldName, Object o) {
        try {

            String firstLetter=fieldName.substring ( 0, 1 ).toUpperCase ( );
            String getter="get" + firstLetter + fieldName.substring ( 1 );
            Method method=o.getClass ( ).getMethod ( getter );
            return method.invoke ( o );
        } catch (Exception e) {
            log.info ( "根据属性名获取属性值异常:" + e.getMessage ( ), e );
            return null;
        }
    }

   /**
     * base64转化为file流
     *
     * @param base64
     * @return
     */
    public static File base64ToFile (String base64) {
        if (base64 == null || "".equals ( base64 )) {
            return null;
        }
        byte[] buff=Base64.getDecoder ( ).decode ( base64 );
        File file=null;
        FileOutputStream out=null;
        try {
            file=File.createTempFile ( "tmp", null );
            out=new FileOutputStream ( file );
            out.write ( buff );
        } catch (IOException e) {
            e.printStackTrace ( );
        } finally {
            if (out != null) {
                try {
                    out.close ( );
                } catch (IOException e) {
                    e.printStackTrace ( );
                }
            }
        }
        return file;
    }

导出数据vo类

public class GysExcelErrorVo {


	/** 对应字段:user_name,备注:用户名称 */
	@ApiModelProperty("用户名称")
	private String userName;
	/** 对应字段:mobile,备注:手机号码 */
	@ApiModelProperty("手机号码")
	private String mobile;
	/** 对应字段:email,备注:邮箱 */
	@ApiModelProperty("邮箱")
	private String email;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用Apache POI和Freemarker两个库来实现根据模板导出数据到word的解决方案。 Apache POI是一个Java API,可以用于读写Microsoft Office格式的文档,包括Word、Excel和PowerPoint等。使用Apache POI,可以在Java程序中创建、修改和读取Word文档,将数据填充到Word文档中的模板中,生成新的Word文档。 Freemarker是一个模板引擎,可以将数据填充到模板中,生成新的文本文件,包括HTML、XML、JSON和Word等。使用Freemarker,可以将数据填充到Word文档中的模板中,生成新的Word文档。 具体实现步骤如下: 1. 创建Word文档模板,使用Word软件设计好需要填充数据的文档模板。 2. 使用Apache POI读取Word文档模板,获取到需要填充数据的位置和格式。 3. 使用Freemarker将数据填充到Word文档模板中,生成新的Word文档。 4. 将生成的新的Word文档保存到文件或输出到浏览器。 这是一个基本的实现流程,具体实现细节可以参考相关的文档和示例代码。以下是一个基本的示例代码: ``` // 1. 创建Word文档模板 FileInputStream fis = new FileInputStream("template.docx"); XWPFDocument templateDoc = new XWPFDocument(fis); fis.close(); // 2. 使用Apache POI读取Word文档模板 for (XWPFParagraph paragraph : templateDoc.getParagraphs()) { List<XWPFRun> runs = paragraph.getRuns(); for (XWPFRun run : runs) { String text = run.getText(0); if (text != null && text.contains("${")) { // 找到需要填充的位置 // 可以使用正则表达式或者字符串替换等方式进行定位 } } } // 3. 使用Freemarker将数据填充到Word文档模板中 Configuration cfg = new Configuration(Configuration.VERSION_2_3_30); cfg.setDefaultEncoding("UTF-8"); cfg.setClassForTemplateLoading(this.getClass(), "/templates"); Template template = cfg.getTemplate("template.ftl"); Map<String, Object> data = new HashMap<>(); data.put("name", "张三"); data.put("age", 20); StringWriter sw = new StringWriter(); template.process(data, sw); String content = sw.toString(); // 4. 将生成的新的Word文档保存到文件或输出到浏览器 XWPFDocument newDoc = new XWPFDocument(); XWPFParagraph newParagraph = newDoc.createParagraph(); XWPFRun newRun = newParagraph.createRun(); newRun.setText(content); FileOutputStream fos = new FileOutputStream("output.docx"); newDoc.write(fos); fos.close(); newDoc.close(); ``` 上述代码使用了一个模板文件`template.ftl`,该文件中包含了需要填充的数据的位置和格式。在代码中,使用Freemarker将数据填充到模板中,生成新的内容`content`,然后将新的内容生成为一个新的Word文档并保存到文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值