freemarker模板操作excel或word

在这里插入图片描述
在这里插入图片描述

<Worksheet ss:Name="Sheet1">
	<Table ss:ExpandedColumnCount="4" ss:ExpandedRowCount="2" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="14.25">
		<Row ss:Height="40">
			<Cell ss:StyleID="s50">
				<Data ss:Type="String">A</Data>
			</Cell>
			<Cell ss:StyleID="s50">
				<Data ss:Type="String">B</Data>
			</Cell>
			<Cell ss:StyleID="s50">
				<Data ss:Type="String">C</Data>
			</Cell>
			<Cell ss:StyleID="s50">
				<Data ss:Type="String">D</Data>
			</Cell>
			<Cell ss:StyleID="s50">
				<Data ss:Type="String">E</Data>
			</Cell>
			<Cell ss:StyleID="s50">
				<Data ss:Type="String">F</Data>
			</Cell>
			<Cell ss:StyleID="s50">
				<Data ss:Type="String">G</Data>
			</Cell>
		</Row>
		<#list list as test>
		<Row>
			<Cell>
				<Data ss:Type="String">${(test.a)!}</Data>
			</Cell>
			<Cell>
				<Data ss:Type="String">${test.b}</Data>
			</Cell>
			<Cell>
				<Data ss:Type="String">${test.c}</Data>
			</Cell>
			<Cell>
				<Data ss:Type="String">${test.d}</Data>
			</Cell>
			<Cell>
				<#if test.e??><Data ss:Type="String">${test.e?string("yyyy-MM-dd")}</Data></#if>
			</Cell>
		    <Cell>
		        <#if test.certType??>
		            <#switch test.certType> 
		                <#case "A"> 
		                    <Data ss:Type="String">■身份证 </Data>
		                <#break> 
		                <#case "B"> 
		                    <Data ss:Type="String">■外籍护照</Data>
		                <#break> 
		                <#case "C"> 
		                    <Data ss:Type="String"> ■港澳居民来往内地通行证</Data>
		                <#break> 
		                <#default> 
		            </#switch>
		            <#else>
		                <Data ss:Type="String">□身份证 □外籍护照 □港澳居民来往内地通行证</Data>
		        </#if>
		    </Cell>
		    <Cell>
				<Data ss:Type="String">${test_index+1}</Data>
			</Cell>
		</Row>
	    </#list>
	</Table>
</Worksheet>
</Workbook>
/**
* 解析模板生成Excel
* @param templateDir  模板目录
* @param templateName 模板名称
* @param excelPath 生成的Excel文件路径
* @param data 数据参数
* @throws IOException
* @throws TemplateException
*/
public static void parse(String templateDir, String templateName, String excelPath, Map<String,Object> data) throws IOException, TemplateException {
   //初始化工作
   Configuration cfg = new Configuration();
   //设置默认编码格式为UTF-8
   cfg.setDefaultEncoding("UTF-8");
   //全局数字格式
   //cfg.setNumberFormat("0.00");
   //设置模板文件位置
   //cfg.setDirectoryForTemplateLoading(new File(templateDir));//目录设置方式
   cfg.setTemplateLoader(new ClassTemplateLoader(EmlsrApplication.class.getClass(),"/"));
   cfg.setObjectWrapper(new DefaultObjectWrapper());
   //加载模板
   Template template = cfg.getTemplate(templateName,"utf-8");
   //OutputStreamWriter writer = null;
   Writer writer = null;
   try{
       //填充数据至Excel
       //response.setContentType("application/msword; charset=UTF-8");// application/x-download
       //response.setHeader("Content-Disposition", "attachment; "
       //+ encodeFileName(request, fileName+".doc"));
       //OutputStream outputStream = response.getOutputStream();
       //Writer out=new OutputStreamWriter(outputStream);
       writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(excelPath),"UTF-8"));
       template.process(data, writer);//下载流换成template.process(data, out);
       writer.flush();
   }finally{
       if (writer!=null) {
           writer.close();
       }
   }
}

//excel->xml->ftl
@Test
public void xls001() throws IOException {
    List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
    for(int i = 0 ; i < 2;i ++){
    	Map<String, Object> user = new HashMap<>();
    	user.put("a","小名1");
    	user.put("b","小红2");
    	user.put("c","小白3");
    	user.put("d","小万4");
    	user.put("e",new Date());
    	user.put("certType","A");
        userList.add(user);
    }
    Map<String,Object> data = new HashMap<String, Object>();
    data.put("list", userList);
    try {
    	parse("", "excel.ftl",
                "E:\\testExcel.xls", data);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TemplateException e) {
        e.printStackTrace();
    }
}

在这里插入图片描述

//doc\docx->xml
@Test
public void word() {
    	try {
    	Map<String,Object> data=new HashMap<String, Object>();
        List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
        for(int i = 0 ; i < 2;i ++){
        	Map<String, Object> user = new HashMap<>();
        	user.put("user_name","小名"+i);
        	user.put("phone","1598623487"+i);
        	user.put("res",i);
        	user.put("id_card","421587922159");
        	
        	Zxing zxing = new  Zxing();
 		    zxing.orCode("www.baidu.com","c:\\qt\\"+i+".jpg");
			user.put("mx",Base64.getEncoder().encodeToString(IOUtils.toByteArray(new FileInputStream("c:\\qt\\"+i+".jpg"))));
           
			userList.add(user);
        }
    	data.put("userList",userList);
		data.put("job","工种");
		data.put("gradeId",2);
		data.put("hg", 20);
		data.put("zgbm","主管部门");
 		data.put("className", "一年级");
		data.put("pxpt", "河南职业培训学校线上平台");
		data.put("major","童年");
 		data.put("classnum","001");
 		data.put("date", new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
		data.put("duration", 45);
		data.put("isbatch", 21);
		parse("", "证明.xml",
                "E:\\证明.doc", data);
    	} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	    }
}

二维码生成

public class Zxing {
	public static void main(String[] args) {
		Zxing zxing = new Zxing();
		zxing.orCode("http://www.baidu.com","c:\\rztj.jpg");
//		zxing.orCode("http://www.zidukeji.com/kstj.html?uid="+1+"&cid="+1+"&eid="+1+"","c:\\evm\\kstj.jpg");
//      http://127.0.0.1:8090/app/pc/sysUser/tj?uid=4410&cid=849&eid=401        

//		File logoFile = new File("E:/QQ.jpg"); // logo
//		File QrCodeFile = new File("E://" + UUID.randomUUID() + ".png");
//		String url = "https://www.baidu.com/?tn=96228755_hao_pg";
//		ZXingCode.drawLogoQRCode(logoFile, QrCodeFile, url);

	}

	public boolean orCode(String content, String path) {
		/*
		 * 图片的宽度和高度
		 */
		int width = 500;
		int height = 500;
		// 图片的格式
		String format = "png";

		// 定义二维码的参数
		HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		// 定义字符集编码格式
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		// 纠错的等级 L > M > Q > H 纠错的能力越高可存储的越少,一般使用M
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		// 设置图片边距
		hints.put(EncodeHintType.MARGIN,2);

		try {
			// 最终生成 参数列表 (1.内容 2.格式 3.宽度 4.高度 5.二维码参数)
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
			// 写入到本地
			Path file = new File(path).toPath();
			MatrixToImageWriter.writeToPath(bitMatrix, format, file);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	private static final int QRCOLOR = 0xFF000000; // 默认是黑色
	private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色
	private static final int WIDTH = 400; // 二维码宽
	private static final int HEIGHT = 400; // 二维码高

	// 用于设置QR二维码参数
	private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
		private static final long serialVersionUID = 1L;
		{
			put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
			put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
		}
	};

	// 生成带logo的二维码图片
	public static void drawLogoQRCode(File logoFile, File codeFile, String qrUrl) {
		try {
			MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
			// 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
			BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
			BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

			// 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
			for (int x = 0; x < WIDTH; x++) {
				for (int y = 0; y < HEIGHT; y++) {
					image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
				}
			}

			int width = image.getWidth();
			int height = image.getHeight();
			if (Objects.nonNull(logoFile) && logoFile.exists()) {
				// 构建绘图对象
				Graphics2D g = image.createGraphics();
				// 读取Logo图片
				BufferedImage logo = ImageIO.read(logoFile);
				// 开始绘制logo图片
				g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
				g.dispose();
				logo.flush();
			}

			image.flush();

			ImageIO.write(image, "png", codeFile); // TODO
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有知识的山巅

文章对你有用,学到了知识。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值