zoukankan      html  css  js  c++  java
  • poi-对于word的操作(一)

    2017-03-02 15:17:30

    使用的jar包是poi 3.13 实现对word的存入,字体、颜色、大小的控制

    测试类:

     1 package poi.test;
     2 
     3 public class WordMain1 {
     4 /** 
     5 * 1.对于word,使用XWPFDocument操作07以上的doc或者docx都没有问题,并且必须是07或者以上的电脑上生成的word 
     6 * 如果是WordExtractor或者HWPFDocument只能操作03以下的word,并且只能是03以下电脑生成的word 
     7 *  
     8 @param args 
     9 */
    10 
    11     public static void main(String[] args) {
    12         String path = "e:\poi\";
    13         String fileName = "poi.docx";
    14         String filePath = path + fileName;
    15         //创建word  
    16         WordUtils1.createWord(path,fileName);
    17         //写入数据  
    18         String data = "本文是以poi3.9读写2010word、2010excel、2010ppt,记录学习的脚步相应的功能在代码都有注释,就不解释了 详情可以参看poi3.9的文档主测试函数 TestMain.java";
    19         WordUtils1.writeDataDocx(filePath,data,true,12);
    20         //WordUtils.writeDataDoc(filePath,data); 
    21         
    22         //读取数据  
    23         //String contentWord=WordUtils.readDataDoc(filePath);  
    24         String contentWord=WordUtils1.readDataDocx(filePath);
    25         System.out.println("word的内容为:
    "+contentWord);
    26         System.out.println();
    27     }
    28 
    29 }

    工具类:

      1 package poi.test;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileNotFoundException;
      6 import java.io.FileOutputStream;
      7 import java.io.IOException;
      8 import java.io.InputStream;
      9 import java.io.OutputStream;
     10 import org.apache.poi.xwpf.usermodel.XWPFDocument;
     11 import org.apache.poi.xwpf.usermodel.XWPFParagraph;
     12 import org.apache.poi.xwpf.usermodel.XWPFRun;
     13 
     14 //创建.doc后缀的word  
     15 public class WordUtils1 {
     16     public static void createWord(String path,String fileName){
     17         //判断目录是否存在  
     18          File file=new File(path);
     19          //exists()测试此抽象路径名表示的文件或目录是否存在。
     20          //mkdir()创建此抽象路径名指定的目录。
     21          //mkdirs()创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。
     22          if(!file.exists()) file.mkdirs();
     23         //因为HWPFDocument并没有提供公共的构造方法 所以没有办法构造word  
     24         //这里使用word2007及以上的XWPFDocument来进行构造word  
     25          @SuppressWarnings("resource")
     26         XWPFDocument document=new XWPFDocument();
     27          OutputStream stream=null;
     28          try {
     29             stream = new FileOutputStream(new File(file, fileName));
     30              document.write(stream);
     31         } catch (FileNotFoundException e) {
     32             e.printStackTrace();
     33         } catch (IOException e) {
     34             e.printStackTrace();
     35         }finally{
     36             if(stream != null);
     37             try {
     38                 stream.close();
     39             } catch (IOException e) {
     40                 e.printStackTrace();
     41             }
     42         }
     43     }
     44     
     45     //向word中写入数据  
     46     /**
     47      * 有些方法需要传特殊类型的参数的时候,一般可以用★静态的接口.参数★来传参
     48      * @param path
     49      * @param data
     50      */
     51     public static void writeDataDocx(String path,String data,boolean jiacu,int size){
     52         InputStream istream=null;
     53         OutputStream ostream=null;
     54         try {
     55             istream = new FileInputStream(path);
     56             ostream = new FileOutputStream(path);
     57             @SuppressWarnings("resource")
     58             XWPFDocument document=new XWPFDocument();
     59             //添加一个段落 
     60             XWPFParagraph p1=document.createParagraph();
     61                         //setAlignment()指定应适用于此段落中的文本的段落对齐方式。CENTER LEFT...
     62                         //p1.setAlignment(ParagraphAlignment.LEFT);
     63                         //p1.setBorderBetween(Borders.APPLES);                       
     64                         //p1.setBorderBottom(Borders.APPLES);
     65                         //p1.setBorderLeft(Borders.APPLES);指定应显示在左边页面指定段周围的边界。
     66                         //p1.setBorderRight(Borders.ARCHED_SCALLOPS);指定应显示在右侧的页面指定段周围的边界。
     67                         //p1.setBorderTop(Borders.ARCHED_SCALLOPS);指定应显示上方一组有相同的一组段边界设置的段落的边界。这几个是对段落之间的格式的统一,相当于格式刷
     68                         //p1.setFirstLineIndent(99);//---正文宽度会稍微变窄
     69                         //p1.setFontAlignment(1);//---段落的对齐方式 1左 2中 3右 4往上 左 不可写0和负数
     70                         //p1.setIndentationFirstLine(400);//---首行缩进,指定额外的缩进,应适用于父段的第一行。
     71                         //p1.setIndentationHanging(400);//---首行前进,指定的缩进量,应通过第一行回到开始的文本流的方向上移动缩进从父段的第一行中删除。
     72                         //p1.setIndentationLeft(400);//---整段缩进(右移)指定应为从左到右段,该段的内容的左边的缘和这一段文字左边的距和右边文本边距和左段权中的那段文本的右边缘之间的缩进,如果省略此属性,则应假定其值为零。
     73                         //p1.setIndentationRight(400);//---指定应放置这一段,该段的内容从左到右段的右边缘的正确文本边距和右边文本边距和左段权中的那段文本的右边缘之间的缩进,如果省略此属性,则应假定其值为零。
     74                         //p1.setIndentFromLeft(400);//---整段右移
     75                         //p1.setIndentFromRight(400);
     76                         //p1.setNumID(BigInteger.TEN);
     77                         //p1.setPageBreak(true);//--指定当渲染此分页视图中的文档,这一段的内容都呈现在文档中的新页的开始。
     78                         //p1.setSpacingAfter(6);//--指定应添加在文档中绝对单位这一段的最后一行之后的间距。
     79                         //p1.setSpacingAfterLines(6);//--指定应添加在此线单位在文档中的段落的最后一行之后的间距。
     80                         //p1.setSpacingBefore(6);//--指定应添加上面这一段文档中绝对单位中的第一行的间距。
     81                         //p1.setSpacingBeforeLines(6);//--指定应添加在此线单位在文档中的段落的第一行之前的间距。
     82                         //p1.setSpacingLineRule(LineSpacingRule.AT_LEAST);//--指定行之间的间距如何计算存储在行属性中。
     83                         //p1.setStyle("");//--此方法提供了样式的段落,这非常有用.
     84                         //p1.setVerticalAlignment(TextAlignment.CENTER);//---指定的文本的垂直对齐方式将应用于此段落中的文本
     85                         //p1.setWordWrapped(true);//--此元素指定是否消费者应中断超过一行的文本范围,通过打破这个词 (打破人物等级) 的两行或通过移动到下一行 (在词汇层面上打破) 这个词的拉丁文字。
     86                         XWPFRun r1=p1.createRun();//p1.createRun()将一个新运行追加到这一段
     87                         //setText(String value)或
     88                         //setText(String value,int pos)
     89                         //value - the literal text which shall be displayed in the document
     90                         //pos - - position in the text array (NB: 0 based)
     91                         r1.setText(data);
     92                         //r1.setTextPosition(20);//这个相当于设置行间距的,具体这个20是怎么算的,不清楚,此元素指定文本应为此运行在关系到周围非定位文本的默认基线升降的量。不是真正意义上的行间距
     93                         //---This element specifies the amount by which text shall be ★raised or lowered★ for this run in relation to the default baseline of the surrounding non-positioned text.
     94                         //r1.setStrike(true);//---设置删除线的,坑人!!!
     95                         //r1.setStrikeThrough(true);---也是设置删除线,可能有细微的区别吧
     96                         //r1.setEmbossed(true);---变的有重影(变黑了一点)
     97                         //r1.setDoubleStrikethrough(true);---设置双删除线
     98                         //r1.setColor("33CC00");//---设置字体颜色 ★
     99                         //r1.setFontFamily("fantasy");
    100                         //r1.setFontFamily("cursive");//---设置ASCII(0 - 127)字体样式 
    101                         r1.setBold(jiacu);//---"加黑加粗"
    102                         r1.setFontSize(size);//---字体大小
    103                         //r1.setImprinted(true);//感觉与setEmbossed(true)类似,有重影
    104                         //r1.setItalic(true);//---文本会有倾斜,是一种字体?
    105                         //r1.setShadow(true);//---文本会变粗有重影,与前面两个有重影效果的方法感觉没什么区别
    106                         //r1.setSmallCaps(true);//---改变了  英文字母  的格式
    107                         //r1.setSubscript(VerticalAlign.BASELINE);//---valign垂直对齐的
    108                         //r1.setUnderline(UnderlinePatterns.DASH);//--填underline type设置下划线
    109                         //document.createTable(2, 2);//--创建一个制定行列的表
    110                         //document.enforceReadonlyProtection();//--强制执行制度保护
    111                         
    112                         /**
    113                          * r1.setDocumentbackground(doc, "FDE9D9");//设置页面背景色
    114                            r1.testSetUnderLineStyle(doc);//设置下划线样式以及突出显示文本
    115                            r1.addNewPage(doc, BreakType.PAGE);
    116                            r1.testSetShdStyle(doc);//设置文字底纹
    117                          */
    118                         document.write(ostream);
    119             System.out.println("创建word成功");
    120         } catch (FileNotFoundException e) {
    121             e.printStackTrace();
    122         } catch (IOException e) {
    123             e.printStackTrace();
    124         }finally{
    125             if(istream!=null){
    126                 try {
    127                     istream.close();
    128                 } catch (IOException e) {
    129                     e.printStackTrace();
    130                 }
    131             }
    132             if(ostream!=null){
    133                 try {
    134                     ostream.close();
    135                 } catch (IOException e) {
    136                     e.printStackTrace();
    137                 }
    138             }
    139         }
    140         }
    141     
    142     //向word中写入数据
    143 //    public static void writeDataDoc(String path,String data){
    144 //        OutputStream ostream=null;
    145 //        try {
    146 //            ostream = new FileOutputStream(path);
    147 //            ostream.write(data.getBytes());
    148 //        } catch (FileNotFoundException e) {
    149 //            e.printStackTrace();
    150 //        } catch (IOException e) {
    151 //            e.printStackTrace();
    152 //        }finally{
    153 //            if(ostream != null){
    154 //                try {
    155 //                    ostream.close();
    156 //                } catch (IOException e) {
    157 //                    e.printStackTrace();
    158 //                }
    159 //            }
    160 //        }
    161 //    }
    162     
    163     //读取数据 docx  
    164     public static String readDataDocx(String filePath) {
    165         String content="";
    166         InputStream istream=null;
    167         try {
    168             istream = new FileInputStream(filePath);
    169             @SuppressWarnings("resource")
    170             XWPFDocument document=new XWPFDocument(istream);
    171             //getLastParagraph()返回包含页眉或页脚的文本的段落
    172             //getText()返回文档所有文本
    173             content=document.getLastParagraph().getText();//★★★★★
    174         } catch (FileNotFoundException e) {
    175             e.printStackTrace();
    176         } catch (IOException e) {
    177             e.printStackTrace();
    178         }finally{
    179             if(istream != null){
    180                 
    181             }
    182         }
    183         return content;
    184     }
    185 }
  • 相关阅读:
    前端构建工具gulp使用
    网页部分内容显示不全
    less简单入门
    jquery——移动端滚动条插件iScroll.js
    css3常用动画+动画库
    windows下nodejs环境配置
    jquery——滚动条插件jscroll.js
    工欲善其事必先利其器——dreamweaver
    jquery常用方法
    nodejs模块——http模块
  • 原文地址:https://www.cnblogs.com/dayuruozhi/p/6490793.html
Copyright © 2011-2022 走看看