如何向word文档写入数据

第二篇文章,代码更精简,增加生成图片的思路

 

大致流程:

1.创建模板docx并取出document.xml

 

新建一个docx文档,放在D盘命名test_template.docx

 

2.用winrar打开test_template.docx,取出word/document.xml

把xml文件格式化一下看起来更清晰,并且把要替换的内容用freemarker的指令代替,最后将文件重命名为test.xml放在D盘下面

3.准备工作完毕,上代码了,这个类是把内容填充到xml

[java] view plain copy

  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.io.Writer;  
  4. import java.util.Map;  
  5.   
  6. import freemarker.template.Configuration;  
  7. import freemarker.template.Template;  
  8. import freemarker.template.TemplateException;  
  9.   
  10. public class XmlToExcel {  
  11.   
  12.     private static XmlToExcel tplm = null;  
  13.     private Configuration cfg = null;  
  14.   
  15.     private XmlToExcel() {  
  16.         cfg = new Configuration();  
  17.         try {  
  18.             // 注册tmlplate的load路径  
  19.             // cfg.setClassForTemplateLoading(this.getClass(), "/template/");  
  20.             cfg.setDirectoryForTemplateLoading(new File("D:/"));  
  21.         } catch (Exception e) {  
  22.   
  23.         }  
  24.     }  
  25.   
  26.     private static Template getTemplate(String name) throws IOException {  
  27.         if (tplm == null) {  
  28.             tplm = new XmlToExcel();  
  29.         }  
  30.         return tplm.cfg.getTemplate(name);  
  31.     }  
  32.   
  33.     /** 
  34.      *  
  35.      * @param templatefile 模板文件 
  36.      * @param param 需要填充的内容 
  37.      * @param out 填充完成输出的文件 
  38.      * @throws IOException 
  39.      * @throws TemplateException 
  40.      */  
  41.     public static void process(String templatefile, Map param, Writer out) throws IOException, TemplateException {  
  42.         // 获取模板  
  43.         Template template = XmlToExcel.getTemplate(templatefile);  
  44.         template.setOutputEncoding("UTF-8");  
  45.         // 合并数据  
  46.         template.process(param, out);  
  47.         if (out != null) {  
  48.             out.close();  
  49.         }  
  50.     }  
  51. }  

4.这个类是把填充完毕的xml转成docx

[java] view plain copy

  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.util.Enumeration;  
  7. import java.util.zip.ZipEntry;  
  8. import java.util.zip.ZipException;  
  9. import java.util.zip.ZipFile;  
  10. import java.util.zip.ZipOutputStream;  
  11.   
  12. /** 
  13.  * 其实docx属于zip的一种,这里只需要操作word/document.xml中的数据,其他的数据不用动 
  14.  *  
  15.  * @author yigehui 
  16.  *  
  17.  */  
  18. public class XmlToDocx {  
  19.   
  20.     /** 
  21.      *  
  22.      * @param documentFile 动态生成数据的docunment.xml文件 
  23.      * @param docxTemplate docx的模板 
  24.      * @param toFileName 需要导出的文件路径 
  25.      * @throws ZipException 
  26.      * @throws IOException 
  27.      */  
  28.   
  29.     public void outDocx(File documentFile, String docxTemplate, String toFilePath) throws ZipException, IOException {  
  30.   
  31.         try {  
  32.             File docxFile = new File(docxTemplate);  
  33.             ZipFile zipFile = new ZipFile(docxFile);  
  34.             Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();  
  35.             ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(toFilePath));  
  36.             int len = -1;  
  37.             byte[] buffer = new byte[1024];  
  38.             while (zipEntrys.hasMoreElements()) {  
  39.                 ZipEntry next = zipEntrys.nextElement();  
  40.                 InputStream is = zipFile.getInputStream(next);  
  41.                 // 把输入流的文件传到输出流中 如果是word/document.xml由我们输入  
  42.                 zipout.putNextEntry(new ZipEntry(next.toString()));  
  43.                 if ("word/document.xml".equals(next.toString())) {  
  44.                     InputStream in = new FileInputStream(documentFile);  
  45.                     while ((len = in.read(buffer)) != -1) {  
  46.                         zipout.write(buffer, 0, len);  
  47.                     }  
  48.                     in.close();  
  49.                 } else {  
  50.                     while ((len = is.read(buffer)) != -1) {  
  51.                         zipout.write(buffer, 0, len);  
  52.                     }  
  53.                     is.close();  
  54.                 }  
  55.             }  
  56.             zipout.close();  
  57.         } catch (Exception e) {  
  58.             e.printStackTrace();  
  59.         }  
  60.     }  
  61. }  

5.main方法调用

[java] view plain copy

  1. public static void main(String[] args) throws IOException, TemplateException {  
  2.   
  3.         try {  
  4.             // xml的文件名  
  5.             String xmlTemplate = "test.xml";  
  6.             // docx的路径和文件名  
  7.             String docxTemplate = "d:\\test_template.docx";  
  8.             // 填充完数据的临时xml  
  9.             String xmlTemp = "d:\\temp.xml";  
  10.             // 目标文件名  
  11.             String toFilePath = "d:\\test.docx";  
  12.   
  13.             Writer w = new FileWriter(new File(xmlTemp));  
  14.             // 1.需要动态传入的数据  
  15.             Map<String, Object> p = new HashMap<String, Object>();  
  16.             List<String> students = new ArrayList<String>();  
  17.             students.add("张三");  
  18.             students.add("李四");  
  19.             students.add("王二");  
  20.             p.put("ddeptdept""研发部门");  
  21.             p.put("ddatedate""2016-12-15");  
  22.             p.put("dnamename", students);  
  23.   
  24.             // 2.把map中的数据动态由freemarker传给xml  
  25.             XmlToExcel.process(xmlTemplate, p, w);  
  26.   
  27.             // 3.把填充完成的xml写入到docx中  
  28.             XmlToDocx xtd = new XmlToDocx();  
  29.             xtd.outDocx(new File(xmlTemp), docxTemplate, toFilePath);  
  30.         } catch (Exception e) {  
  31.             e.printStackTrace();  
  32.         }  
  33.     }  
  34.  
1.所需的三个控件: ChooseWA: TWordApplication; ChooseWD: TWordDocument; ChooseWF: TWordFont; 2.检查计算机是否安装了WORD try ChooseWA.Connect; except MessageBox(handle,'无法链接,请确认电脑上是否安装Word XP/2003及以上版本','连接出错', MB_Ok or MB_ICONERROR); Abort; end; 3.关闭WORD拼写检查 //因为Word进行拼写检查需要很多时间,所以首先关闭检查 ChooseWA.Options.CheckSpellingAsYouType := False; ChooseWA.Options.CheckGrammarAsYouType := False; 4.新建一个文档并设置文档的标题 var NewDocument: _Document; ItemIndex: OleVariant; ItemIndex := 1; NewDocument := ChooseWA.Documents.Add(EmptyParam,EmptyParam,EmptyParam,EmptyParam); ChooseWD.ConnectTo(NewDocument); ChooseWD.Windows.Item(ItemIndex).Caption := '我新建的第一个文档';//此文档的第一个窗口的标题,试卷 名称 5.写入数据 ChooseWD.Range.InsertAfter('第一行数据'+#13);//#13代表换行 6.设置字体格式 procedure SetFont(aBold,aItalic,aShadow,aSize:integer); begin ChooseWF.ConnectTo(ChooseWD.Sentences.Get_Last.Font); ChooseWF.Name := '宋体'; ChooseWF.Bold := aBold; ChooseWF.Italic := aItalic; ChooseWF.Shadow := aShadow; ChooseWF.Size := aSize; end; 如:SetFont(1,0,0,22);//设置字体为22号 7.向WORD写入表格 (1)插入表格: ChooseWD.Tables.Add(ChooseWD.Words.Last, RowNum, ColNum,EmptyParam,EmptyParam);//RowNum为行数, ColNum为列数 (2)插入数据: ChooseWD.Tables.Item(1).Cell(1,1).Range.Text := '第一行第一列'; ChooseWD.Tables.Item(1).Cell(2,1).Range.Text := '第二行第一列'; 8.向WORD写入图片 var Img: TImage; MyFormat: Word; AData: Cardinal; APalette: HPALETTE; Img.Picture.LoadFromFile('文件路径');//从文件夹中导入图片至控件 Img.Picture.SaveToClipboardFormat(MyFormat,AData,APalette);//将图片转存到剪贴板中 Clipboard.SetAsHandle(MyFormat,AData);//将剪贴板中的图片复制出来,注意添加Clipbrd单元 ChooseWD.Sentences.Last.Paste;//在WORD中粘贴图片 9.在界面中显示WORD文档 ChooseWA.Visible:=true; 10.断开与WORD的链接 ChooseWA.Disconnect; ChooseWD.Disconnect; Chart1.SaveToBitmapFile(‘文件名.bmp’);
用对象纯源码实现word的操作,纯绿色,无公害. 关于 易语言 操作word读写或者向word中插入图片的实现,经大量搜索贴子,发现基本思路是明白了(用com对象操作),但是例子代码太少,同时有的代码写法不够严谨或者使用模块等,导致实现效果不理想,也不容易理解.因此开贴,给新人及我等小白做个总结,以便简单操作word.相信本贴子能让你很快入门word的基本操作. 提示: word操作,使用对象进行,关于如何学习的问题,给新人们几点建议: 1,VBAword.chm 这个知识库肯定是得看的,方便查找对象,属性,方法等; 2,对象.查看(),这个命令是必须使用的,同样是方便查找对象,方法,并了解在易语言中,到底该用.读对象属性(),还是.对象型方法(); 3,记住几个主要的对象:application, document, selection, table, cell, range 4,操作的思想: 找到对象( .读对象属性() )-->处理对象( .对象型方法() ) 本贴关于创建word文档等基本的就不说了,主要是对打开的word文档进行操作,实现了以下主要功能: 主要功能: 1,表格中定位插入图片 2,表格中定位单元格 填 内容 3, doc文档中按行定位并写入文本 4,doc文档中按表格定位到第一个单元格并写入文本 5,doc文档中精确定位到表格单元格并写入文本 6,表格中左右移动并写入文本 7,表格中上下移动并写入文本 8,定位后插入空表格 9,查找文本进行替换(这个基本功能论坛很多贴子都有,我就不写了,大家总结别人的用吧) 下面是执行后的效果 :
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值