freemarker模板操作excel或word


java 复制代码
<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();
    }
}
java 复制代码
//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();
	    }
}

二维码生成

java 复制代码
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();
		}
	}
}
相关推荐
小蜗牛慢慢爬行2 分钟前
有关异步场景的 10 大 Spring Boot 面试问题
java·开发语言·网络·spring boot·后端·spring·面试
新手小袁_J27 分钟前
JDK11下载安装和配置超详细过程
java·spring cloud·jdk·maven·mybatis·jdk11
呆呆小雅27 分钟前
C#关键字volatile
java·redis·c#
Monly2128 分钟前
Java(若依):修改Tomcat的版本
java·开发语言·tomcat
Ttang2330 分钟前
Tomcat原理(6)——tomcat完整实现
java·tomcat
钱多多_qdd41 分钟前
spring cache源码解析(四)——从@EnableCaching开始来阅读源码
java·spring boot·spring
waicsdn_haha43 分钟前
Java/JDK下载、安装及环境配置超详细教程【Windows10、macOS和Linux图文详解】
java·运维·服务器·开发语言·windows·后端·jdk
Q_19284999061 小时前
基于Spring Boot的摄影器材租赁回收系统
java·spring boot·后端
Code_流苏1 小时前
VSCode搭建Java开发环境 2024保姆级安装教程(Java环境搭建+VSCode安装+运行测试+背景图设置)
java·ide·vscode·搭建·java开发环境
禁默2 小时前
深入浅出:AWT的基本组件及其应用
java·开发语言·界面编程