freemarker利用xml形式​导出word文档

package test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.thoughtworks.xstream.core.util.Base64Encoder;



import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Exportdoc {
		
		//配置
		private Configuration configuration = null;
		
		public Exportdoc() {
			configuration = new Configuration();
			configuration.setDefaultEncoding("UTF-8");
		}
		
		/*
		 * modelName:模版名称
		 * exportFilePath:文件路径
		 * 
		 */
		public void createdoc(String modelName, String exportFilePath){
			
			Template template = null;
			
			//导入模版
			configuration.setClassForTemplateLoading(this.getClass(), "");
			
			try {
				template = configuration.getTemplate(modelName);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			Map<String, Object> dataMap = new HashMap<String, Object>();
			getData(dataMap);
			
			//导出文件
			//输出流
			File outfile = new File(exportFilePath);
			Writer writer = null;
			
			try {
				writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile),"utf-8"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				
				template.process(dataMap, writer);
				
			} catch (TemplateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		
		
		//把数据打包成map;dataMap里存放的数据Key值要与模板中的参数相对应
		private void getData(Map<String, Object> dataMap) {
			
			dataMap.put("author", "shan");
			dataMap.put("remark", "这是测试备注信息");
			dataMap.put("image", getImageStr());
			
			List<table> table1 = new ArrayList<table>();

			table t1 = new table();
			t1.setDate("2015-11-16");
			t1.setText("测试信息1");
			table1.add(t1);

			table t2 = new table();
			t2.setDate("2015-11-16");
			t2.setText("测试信息2");
			table1.add(t2);
			
			//放入map集合
			dataMap.put("table", table1);
			
			//创建list集合
			List<table1> table = new ArrayList<table1>();
			
			//循环存储数据
			for (int i = 0; i < 10; i++) {
				
				table1 t = new table1();
				
				t.setSequence(i + 1 + "");
				t.setDetail("测试计划" + i);
				t.setPerson("shan"+ i);
				t.setBegindate("2015-11-1");
				t.setFinishdate("2015-11-31");
				t.setDescription("备注信息"+i);
				
				table.add(t);

			}
			//添加至集合
			dataMap.put("table1", table);

		}
		
		//添加图片
		private String getImageStr() {
	        String imgFile = "E:/Workspaces/ExportDoc/bin/test/test1.jpg";
	        InputStream in = null;
	        byte[] data = null;
	        try {
	            in = new FileInputStream(imgFile);
	            data = new byte[in.available()];
	            in.read(data);
	            in.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        Base64Encoder encoder = new Base64Encoder();
	        return encoder.encode(data);
	    }
		
		//测试
		public static void main(String[] args) {
			
			Exportdoc ex = new Exportdoc();
			//模版位置
			String modelName = "masterplate.xml";
			//导出位置
			String filepath = "D:/demo.doc"; 
			ex.createdoc(modelName, filepath);
			System.out.println("导出成功"+filepath);
			
			
		}
}



package test;

public class table {
	
	private String date;
	private String text;
	
	
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	
	

}



package test;

public class table1 {
	
	private String sequence;
	private String detail;
	private String person;
	private String description;
	private String begindate;
	private String finishdate;
	
	
	public String getSequence() {
		return sequence;
	}
	public void setSequence(String sequence) {
		this.sequence = sequence;
	}
	public String getDetail() {
		return detail;
	}
	public void setDetail(String detail) {
		this.detail = detail;
	}
	public String getPerson() {
		return person;
	}
	public void setPerson(String person) {
		this.person = person;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getBegindate() {
		return begindate;
	}
	public void setBegindate(String begindate) {
		this.begindate = begindate;
	}
	public String getFinishdate() {
		return finishdate;
	}
	public void setFinishdate(String finishdate) {
		this.finishdate = finishdate;
	}
	
	
}


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument xmlns:aml="http://schemas.microsoft.com/aml/2001/core"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:w10="urn:schemas-microsoft-com:office:word"
xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml"
xmlns:wx="http://schemas.microsoft.com/office/word/2003/auxHint"
xmlns:wsp="http://schemas.microsoft.com/office/word/2003/wordml/sp2"
xmlns:sl="http://schemas.microsoft.com/schemaLibrary/2003/core"
w:macrosPresent="no" w:embeddedObjPresent="no" w:ocxPresent="no"
xml:space="preserve"><w:ignoreSubtree
w:val="http://schemas.microsoft.com/office/word/2003/wordml/sp2" /><o:DocumentProperties><o:Author>yq</o:Author><o:LastAuthor>yq</o:LastAuthor><o:Revision>2</o:Revision><o:TotalTime>4</o:TotalTime><o:Created>2015-11-16T08:09:00Z</o:Created><o:LastSaved>2015-11-16T08:09:00Z</o:LastSaved><o:Pages>1</o:Pages><o:Words>31</o:Words><o:Characters>179</o:Characters><o:Lines>1</o:Lines><o:Paragraphs>1</o:Paragraphs><o:CharactersWithSpaces>209</o:CharactersWithSpaces><o:Version>12</o:Version>
</o:DocumentProperties><w:fonts><w:defaultFonts w:ascii="Calibri"
w:fareast="宋体" w:h-ansi="Calibri" w:cs="Times New Roman" /><w:font
w:name="Times New Roman"><w:panose-1
w:val="02020603050405020304" /><w:charset w:val="00" /><w:family
w:val="Roman" /><w:pitch w:val="variable" /><w:sig
w:usb-0="20002A87" w:usb-1="80000000" w:usb-2="00000008"
w:usb-3="00000000" w:csb-0="000001FF" w:csb-1="00000000" />
</w:font><w:font w:name="宋体"><w:altName w:val="SimSun" /><w:panose-1
w:val="02010600030101010101" /><w:charset w:val="86" /><w:family
w:val="auto" /><w:pitch w:val="variable" /><w:sig
w:usb-0="00000003" w:usb-1="080E0000" w:usb-2="00000010"
w:usb-3="00000000" w:csb-0="00040001" w:csb-1="00000000" />
</w:font><w:font w:name="Cambria Math"><w:panose-1
w:val="02040503050406030204" /><w:charset w:val="00" /><w:family
w:val="Roman" /><w:pitch w:val="variable" /><w:sig
w:usb-0="A00002EF" w:usb-1="420020EB" w:usb-2="00000000"
w:usb-3="00000000" w:csb-0="0000009F" w:csb-1="00000000" />
</w:font><w:font w:name="Calibri"><w:panose-1
w:val="020F0502020204030204" /><w:charset w:val="00" /><w:family
w:val="Swiss" /><w:pitch w:val="variable" /><w:sig
w:usb-0="A00002EF" w:usb-1="4000207B" w:usb-2="00000000"
w:usb-3="00000000" w:csb-0="0000009F" w:csb-1="00000000" />
</w:font><w:font w:name="@宋体"><w:panose-1 w:val="02010600030101010101" /><w:charset
w:val="86" /><w:family w:val="auto" /><w:pitch
w:val="variable" /><w:sig w:usb-0="00000003"
w:usb-1="080E0000" w:usb-2="00000010" w:usb-3="00000000"
w:csb-0="00040001" w:csb-1="00000000" />
</w:font>
</w:fonts><w:styles><w:versionOfBuiltInStylenames w:val="7" /><w:latentStyles
w:defLockedState="off" w:latentStyleCount="267"><w:lsdException
w:name="Normal" /><w:lsdException w:name="heading 1" /><w:lsdException
w:name="heading 2" /><w:lsdException w:name="heading 3" /><w:lsdException
w:name="heading 4" /><w:lsdException w:name="heading 5" /><w:lsdException
w:name="heading 6" /><w:lsdException w:name="heading 7" /><w:lsdException
w:name="heading 8" /><w:lsdException w:name="heading 9" /><w:lsdException
w:name="caption" /><w:lsdException w:name="Title" /><w:lsdException
w:name="Subtitle" /><w:lsdException w:name="Strong" /><w:lsdException
w:name="Emphasis" /><w:lsdException w:name="No Spacing" /><w:lsdException
w:name="List Paragraph" /><w:lsdException
w:name="Quote" /><w:lsdException w:name="Intense Quote" /><w:lsdException
w:name="Subtle Emphasis" /><w:lsdException
w:name="Intense Emphasis" /><w:lsdException
w:name="Subtle Reference" /><w:lsdException
w:name="Intense Reference" /><w:lsdException
w:name="Book Title" /><w:lsdException
w:name="TOC Heading" />
</w:latentStyles><w:style w:type="paragraph" w:default="on"
w:styleId="a"><w:name w:val="Normal" /><wx:uiName
wx:val="正文" /><w:rsid w:val="00607186" /><w:pPr><w:widowControl
w:val="off" /><w:jc w:val="both" />
</w:pPr><w:rPr><wx:font wx:val="Calibri" /><w:kern w:val="2" /><w:sz
w:val="21" /><w:sz-cs w:val="22" /><w:lang
w:val="EN-US" w:fareast="ZH-CN" w:bidi="AR-SA" />
</w:rPr>
</w:style><w:style w:type="character" w:default="on" w:styleId="a0"><w:name
w:val="Default Paragraph Font" /><wx:uiName
wx:val="默认段落字体" />
</w:style><w:style w:type="table" w:default="on" w:styleId="a1"><w:name
w:val="Normal Table" /><wx:uiName wx:val="普通表格" /><w:rPr><wx:font
wx:val="Calibri" /><w:lang w:val="EN-US"
w:fareast="ZH-CN" w:bidi="AR-SA" />
</w:rPr><w:tblPr><w:tblInd w:w="0" w:type="dxa" /><w:tblCellMar><w:top
w:w="0" w:type="dxa" /><w:left w:w="108"
w:type="dxa" /><w:bottom w:w="0" w:type="dxa" /><w:right
w:w="108" w:type="dxa" />
</w:tblCellMar>
</w:tblPr>
</w:style><w:style w:type="list" w:default="on" w:styleId="a2"><w:name
w:val="No List" /><wx:uiName wx:val="无列表" />
</w:style><w:style w:type="table" w:styleId="a3"><w:name
w:val="Table Grid" /><wx:uiName wx:val="网格型" /><w:basedOn
w:val="a1" /><w:rsid w:val="00515999" /><w:rPr><wx:font
wx:val="Calibri" />
</w:rPr><w:tblPr><w:tblInd w:w="0" w:type="dxa" /><w:tblBorders><w:top
w:val="single" w:sz="4" wx:bdrwidth="10" w:space="0"
w:color="000000" /><w:left w:val="single"
w:sz="4" wx:bdrwidth="10" w:space="0" w:color="000000" /><w:bottom
w:val="single" w:sz="4" wx:bdrwidth="10" w:space="0"
w:color="000000" /><w:right w:val="single"
w:sz="4" wx:bdrwidth="10" w:space="0" w:color="000000" /><w:insideH
w:val="single" w:sz="4" wx:bdrwidth="10" w:space="0"
w:color="000000" /><w:insideV w:val="single"
w:sz="4" wx:bdrwidth="10" w:space="0" w:color="000000" />
</w:tblBorders><w:tblCellMar><w:top w:w="0" w:type="dxa" /><w:left
w:w="108" w:type="dxa" /><w:bottom w:w="0"
w:type="dxa" /><w:right w:w="108" w:type="dxa" />
</w:tblCellMar>
</w:tblPr>
</w:style>
</w:styles><w:shapeDefaults><o:shapedefaults
spidmax="2050" /><o:shapelayout ><o:idmap
data="1" />
</o:shapelayout>
</w:shapeDefaults><w:docPr><w:view w:val="print" /><w:zoom
w:percent="100" /><w:doNotEmbedSystemFonts /><w:bordersDontSurroundHeader /><w:bordersDontSurroundFooter /><w:proofState
w:spelling="clean" w:grammar="clean" /><w:defaultTabStop
w:val="420" /><w:drawingGridVerticalSpacing w:val="156" /><w:displayHorizontalDrawingGridEvery
w:val="0" /><w:displayVerticalDrawingGridEvery w:val="2" /><w:punctuationKerning /><w:characterSpacingControl
w:val="CompressPunctuation" /><w:optimizeForBrowser /><w:validateAgainstSchema /><w:saveInvalidXML
w:val="off" /><w:ignoreMixedContent w:val="off" /><w:alwaysShowPlaceholderText
w:val="off" /><w:compat><w:spaceForUL /><w:balanceSingleByteDoubleByteWidth /><w:doNotLeaveBackslashAlone /><w:ulTrailSpace /><w:doNotExpandShiftReturn /><w:adjustLineHeightInTable /><w:breakWrappedTables /><w:snapToGridInCell /><w:wrapTextWithPunct /><w:useAsianBreakRules /><w:dontGrowAutofit /><w:useFELayout />
</w:compat><wsp:rsids><wsp:rsidRoot wsp:val="00515999" /><wsp:rsid
wsp:val="00385AD6" /><wsp:rsid wsp:val="004361F0" /><wsp:rsid
wsp:val="00515999" /><wsp:rsid wsp:val="00607186" /><wsp:rsid
wsp:val="00816293" /><wsp:rsid wsp:val="00872D9D" /><wsp:rsid
wsp:val="009C3897" /><wsp:rsid wsp:val="00AF1C3B" /><wsp:rsid
wsp:val="00D764A5" /><wsp:rsid wsp:val="00FB62F1" />
</wsp:rsids>
</w:docPr><w:body><w:p wsp:rsidR="00BC65CD" wsp:rsidRDefault="00515999"
wsp:rsidP="00385AD6"><w:pPr><w:jc w:val="center" /><w:rPr><w:b /><w:sz
w:val="28" /><w:sz-cs w:val="28" />
</w:rPr>
</w:pPr><w:r wsp:rsidRPr="00385AD6"><w:rPr><w:rFonts w:hint="fareast" /><w:b /><w:sz
w:val="28" /><w:sz-cs w:val="28" />
</w:rPr><w:t>2015</w:t>
</w:r><w:r wsp:rsidRPr="00385AD6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java导出Word文档可以利用Apache POI和Freemarker模板引擎来实现。 Apache POI是一个用于操作Microsoft Office文档的Java API。它提供了对Word文档的读取、创建和修改的功能。通过使用Apache POI,可以轻松地在Java代码中创建一个空的Word文档,并添加文本、表格、图片等内容。同时,还可以设置文档的样式、格式和布局等,以满足不同的需求。 而Freemarker模板引擎则是用于生成动态文本输出的工具。它基于模板和数据模型,可以将数据动态填充到指定的Word模板中,生成最终的Word文档。使用Freemarker模板引擎可以使文档的生成更加灵活和可扩展,根据不同的数据模型生成不同的文档内容,提高了代码的可维护性和重用性。 要实现导出Word文档的功能,首先需要引入Apache POI和Freemarker的相关依赖库。接下来,创建一个空的Word文档,使用Apache POI的API对文档进行操作,例如添加标题、段落、表格等内容,以及设置样式和格式。然后,结合Freemarker模板引擎,根据自定义的数据模型填充数据到Word模板中,生成最终的Word文档。 通过以上的方法,利用Apache POI和Freemarker模板引擎可以轻松地实现Java导出Word文档的功能。这种方式方便、灵活,适用于需要动态生成Word文档的各种场景,例如报告生成、合同生成等。同时,这两个工具库都有良好的文档和丰富的示例代码,方便开发者进行学习和使用。 ### 回答2: Java 导出 Word 文档利用 Apache POI 和 FreeMarker 模板引擎的基本步骤如下: 1. 首先,确保你的项目已经导入了 Apache POI 和 FreeMarker 的相关依赖。 2. 创建一个 Word 文档模板,可以使用 Microsoft Office 软件创建一个空白文档,并将需要的样式和占位符添加到模板中。占位符可以使用自定义的标记,例如 `${name}`。 3. 在 Java 代码中,使用 Apache POI 创建一个 Word 文档对象 `XWPFDocument`。例如:`XWPFDocument document = new XWPFDocument();`。 4. 使用 FreeMarker 模板引擎加载并解析 Word 文档模板。创建一个 `Configuration` 对象,并设置模板文件的路径或类路径。例如:`Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);`。 5. 根据模板文件路径或类路径加载模板文件。例如:`Template template = configuration.getTemplate("template.docx");`。 6. 创建一个数据模型,将数据填充到模板中。可以使用 `Map` 或自定义的 Java 对象作为数据模型。例如:`Map<String, String> data = new HashMap<>();`,然后将需要填充的数据放入 `data` 中。 7. 使用 FreeMarker 模板引擎的 `process` 方法将数据模型与模板进行合并,生成最终的 Word 文档内容。例如:`StringWriter writer = new StringWriter();`,`template.process(data, writer);`。 8. 将生成的 Word 文档内容写入到 Apache POI 的 `XWPFDocument` 对象中。可以使用 `OutputStream` 将内容写入到文档对象中。例如:`OutputStream outputStream = new FileOutputStream("output.docx");`,`writer.flush();`,`document.write(outputStream);`,`outputStream.close();`。 9. 最后,记得在使用完毕后关闭相关资源,例如关闭输出流、释放内存等。 以上就是利用 Apache POI 和 FreeMarker 模板引擎导出 Word 文档的基本步骤,通过动态填充数据,可以生成灵活且具有个性化内容的 Word 文档。 ### 回答3: Java导出Word文档可以使用Apache POI和Freemarker模板引擎相结合的方法来实现。Apache POI是一个用于处理Microsoft Office文档的Java库,而Freemarker是一个基于模板的文本生成引擎。 首先,我们需要在项目中引入Apache POI和Freemarker的相关依赖。 然后,我们需要创建一个Word文档的模板文件,模板文件中可以包含一些占位符,用于动态添加数据。比如,我们可以在模板文件中添加一个{{name}}的占位符。 接下来,在Java中,我们可以使用Freemarker来解析模板文件。首先,我们需要创建一个Configuration对象,并指定模板文件的路径。然后,我们可以使用Template类的getTemplate方法来获取模板对象。 接着,我们可以创建一个Map对象,将需要动态添加的数据放入其中。比如,我们可以将姓名(name)放入Map中。 然后,我们可以调用Template类的process方法来解析模板并将数据填充到占位符中。我们可以将解析后的结果保存在一个字符串中。 最后,我们可以使用Apache POI来创建一个新的Word文档。我们可以创建一个XWPFDocument对象,并使用其createParagraph方法来创建段落。然后,我们可以使用XWPFRun对象的setText方法将之前解析后的结果添加到段落中。 最后,我们可以将生成的Word文档保存到指定路径。我们可以使用XWPFDocument对象的write方法将文档保存为文件。 综上所述,通过使用Apache POI和Freemarker模板引擎,我们可以方便地导出Word文档。我们只需要创建一个模板文件,使用Freemarker来解析模板并将数据填充到占位符中,然后使用Apache POI来创建新的文档并保存即可。这种方法可以加快开发速度,同时也使得代码结构更加清晰易读。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值