用java生成word文档(转载)

用java生成word文档
poi是apache的一个项目,不过就算用poi你可能都觉得很烦,不过不要紧,这里提供了更加简单的一个接口给你:
下载经过封装后的poi包:

下载之后,放到你的classpath就可以了,下面是如何使用它的一个例子:
import java.io.*;
import org.textmining.text.extraction.WordExtractor;
/**
*

Title: pdf extraction


*

Description: email:chris@matrix.org.cn


*

Copyright: Matrix Copyright (c) 2003


*

Company: Matrix.org.cn


* @author chris
* @version 1.0,who use this example pls remain the declare
*/

public class PdfExtractor {
public PdfExtractor() {
}
public static void main(String args[]) throws Exception
{
FileInputStream in = new FileInputStream ("c://a.doc");
WordExtractor extractor = new WordExtractor();
String str = extractor.extractText(in);
System.out.println("the result length is"+str.length());
System.out.println("the result is"+str);
}
}

如果没有这个包呢?就是下面这段了

read word:

代码
  1. public class WordExtractor {   
  2.     public WordExtractor() {   
  3.     }   
  4.   
  5.     public String extractText(InputStream in) throws IOException {   
  6.         ArrayList text = new ArrayList();   
  7.         POIFSFileSystem fsys = new POIFSFileSystem(in);   
  8.   
  9.         DocumentEntry headerProps = (DocumentEntry) fsys.getRoot().getEntry("WordDocument");   
  10.         DocumentInputStream din = fsys.createDocumentInputStream("WordDocument");   
  11.         byte[] header = new byte[headerProps.getSize()];   
  12.   
  13.         din.read(header);   
  14.         din.close();   
  15.         // Prende le informazioni dall'header del documento   
  16.         int info = LittleEndian.getShort(header, 0xa);   
  17.   
  18.         boolean useTable1 = (info & 0x200) != 0;   
  19.   
  20.         //boolean useTable1 = true;   
  21.            
  22.         // Prende informazioni dalla piece table   
  23.         int complexOffset = LittleEndian.getInt(header, 0x1a2);   
  24.         //int complexOffset = LittleEndian.getInt(header);   
  25.            
  26.         String tableName = null;   
  27.         if (useTable1) {   
  28.             tableName = "1Table";   
  29.         } else {   
  30.             tableName = "0Table";   
  31.         }   
  32.   
  33.         DocumentEntry table = (DocumentEntry) fsys.getRoot().getEntry(tableName);   
  34.         byte[] tableStream = new byte[table.getSize()];   
  35.   
  36.         din = fsys.createDocumentInputStream(tableName);   
  37.   
  38.         din.read(tableStream);   
  39.         din.close();   
  40.   
  41.         din = null;   
  42.         fsys = null;   
  43.         table = null;   
  44.         headerProps = null;   
  45.   
  46.         int multiple = findText(tableStream, complexOffset, text);   
  47.   
  48.         StringBuffer sb = new StringBuffer();   
  49.         int size = text.size();   
  50.         tableStream = null;   
  51.   
  52.         for (int x = 0; x < size; x++) {   
  53.                
  54.             WordTextPiece nextPiece = (WordTextPiece) text.get(x);   
  55.             int start = nextPiece.getStart();   
  56.             int length = nextPiece.getLength();   
  57.   
  58.             boolean unicode = nextPiece.usesUnicode();   
  59.             String toStr = null;   
  60.             if (unicode) {   
  61.                 toStr = new String(header, start, length * multiple, "UTF-16LE");   
  62.             } else {   
  63.                 toStr = new String(header, start, length, "ISO-8859-1");   
  64.             }   
  65.             sb.append(toStr).append(" ");   
  66.   
  67.         }   
  68.         return sb.toString();   
  69.     }   
  70.   
  71.     private static int findText(byte[] tableStream, int complexOffset, ArrayList text)   
  72.         throws IOException {   
  73.         //actual text   
  74.         int pos = complexOffset;   
  75.         int multiple = 2;   
  76.         //skips through the prms before we reach the piece table. These contain data   
  77.         //for actual fast saved files   
  78.         while (tableStream[pos] == 1) {   
  79.             pos++;   
  80.             int skip = LittleEndian.getShort(tableStream, pos);   
  81.             pos += 2 + skip;   
  82.         }   
  83.         if (tableStream[pos] != 2) {   
  84.             throw new IOException("corrupted Word file");   
  85.         } else {   
  86.             //parse out the text pieces   
  87.             int pieceTableSize = LittleEndian.getInt(tableStream, ++pos);   
  88.             pos += 4;   
  89.             int pieces = (pieceTableSize - 4) / 12;   
  90.             for (int x = 0; x < pieces; x++) {   
  91.                 int filePos =   
  92.                     LittleEndian.getInt(tableStream, pos + ((pieces + 1) * 4) + (x *"/images/forum/smiles/icon_cool.gif"/> + 2);   
  93.                 boolean unicode = false;   
  94.                 if ((filePos & 0x40000000) == 0) {   
  95.                     unicode = true;   
  96.                 } else {   
  97.                     unicode = false;   
  98.                     multiple = 1;   
  99.                     filePos &= ~(0x40000000); //gives me FC in doc stream   
  100.                     filePos /= 2;   
  101.                 }   
  102.                 int totLength =   
  103.                     LittleEndian.getInt(tableStream, pos + (x + 1) * 4)   
  104.                         - LittleEndian.getInt(tableStream, pos + (x * 4));   
  105.   
  106.                 WordTextPiece piece = new WordTextPiece(filePos, totLength, unicode);   
  107.                 text.add(piece);   
  108.   
  109.             }   
  110.   
  111.         }   
  112.         return multiple;   
  113.     }   
  114.     public static void main(String[] args){   
  115.         WordExtractor w  = new WordExtractor();   
  116.         POIFSFileSystem ps = new POIFSFileSystem();   
  117.         try{   
  118.                
  119.             File file = new File("C://test.doc");   
  120.                
  121.             InputStream in = new FileInputStream(file);   
  122.             String s = w.extractText(in);   
  123.             System.out.println(s);   
  124.        
  125.                
  126.         }catch(Exception e){   
  127.             e.printStackTrace();   
  128.         }   
  129.                    
  130.     }   
  131.   
  132. }   
  133. class WordTextPiece {   
  134.     private int _fcStart;   
  135.     private boolean _usesUnicode;   
  136.     private int _length;   
  137.   
  138.     public WordTextPiece(int start, int length, boolean unicode) {   
  139.         _usesUnicode = unicode;   
  140.         _length = length;   
  141.         _fcStart = start;   
  142.     }   
  143.     public boolean usesUnicode() {   
  144.         return _usesUnicode;   
  145.     }   
  146.   
  147.     public int getStart() {   
  148.         return _fcStart;   
  149.     }   
  150.     public int getLength() {   
  151.         return _length;   
  152.     }   
  153.   
  154. }   
<script>render_code();</script>

 

write word

 

代码
  1. public boolean writeWordFile(String path, String content) {   
  2.     boolean w = false;   
  3.     try {   
  4.   
  5.     //  byte b[] = content.getBytes("ISO-8859-1");   
  6.         byte b[] = content.getBytes();   
  7.            
  8.         ByteArrayInputStream bais = new ByteArrayInputStream(b);   
  9.   
  10.         POIFSFileSystem fs = new POIFSFileSystem();   
  11.         DirectoryEntry directory = fs.getRoot();   
  12.   
  13.         DocumentEntry de = directory.createDocument("WordDocument", bais);   
  14.   
  15.         FileOutputStream ostream = new FileOutputStream(path);   
  16.   
  17.         fs.writeFilesystem(ostream);   
  18.            
  19.         bais.close();   
  20.         ostream.close();   
  21.   
  22.     } catch (IOException e) {   
  23.         e.printStackTrace();   
  24.     }   
  25.   
  26.     return w;   
  27. }   
<script>render_code();</script>

写操作的代码还是有些问题:打开WORD时提示要选择字符类型
希望能改进!

 这样写文件有问题,因为不是word格式。

当然这几个jar是少不了的
poi-2.5.1-final-20040804.jar
poi-contrib-2.5.1-final-20040804.jar
poi-scratchpad-2.5.1-final-20040804.jar

如果要直接用Jakarta POI HWPF,没提供编译好的下载,只是原码了,自己编译吧
jakarta POI开源项目组HWPF(在下载后的scratchpad目录里)是操作word文档,在这里作了个简单的例子
下载地址: http://www.apache.org/dist/jakarta/Poi/

<!--age contentType="text/html; charset=GBK" import="java.io.*,org.apache.poi.hwpf.HWPFDocument,org.apache.poi.hwpf.usermodel.*,org.apache.poi.hwpf.model.*"-->









<!--r /> HWPFDocument doc = new HWPFDocument(new FileInputStream("g://a.doc"));<br /> Range r = doc.getRange ();   //取得word文档的范围<br />   StyleSheet styleSheet = doc.getStyleSheet ();<br /> <br />   int sectionLevel = 0;<br />   int lenParagraph = r.numParagraphs ();//取得段落数<br />   int c=r.numCharacterRuns();<br />   int b=r.numSections();<br />   String s=r.text();<br />   boolean inCode = false;<br />   // Paragraph p;<br />   for (int x = 0; x < lenParagraph; x++)<br />   {<br />     Paragraph p = r.getParagraph (x);<br /> <br />     String text = p.text ();<br />    -->


    <!--ex-->

<!--r />     if (text.trim ().length () == 0)<br />     {<br />     continue;<br />     }<br /> <br /> <br />     }<br /> <br />   //doc.write(new FileOutputStream("g://b.doc"));<br /> <br /> <br /> <br /> -->
char:

section:

text:



 

 

 

 


java操作word,可以试试java2word 

 java2word 是一个在java程序中调用 MS Office Word 文档的组件(类库)。该组件提供了一组简单的接口,以便java程序调用他的服务操作Word 文档。
这些服务包括:
打开文档、新建文档、查找文字、替换文字,
插入文字、插入图片、插入表格,
在书签处插入文字、插入图片、插入表格等。
填充数据到表格中读取表格数据
1.1版增强的功能:
@指定文本样式,指定表格样式。如此,则可动态排版word文档。
@填充表格数据时,可指定从哪行哪列开始填充。配合输入数据的大小,你可以修改表中的任意部分,甚至只修改一个单元格的内容。
@合并单元格。
更多激动人心的功能见详细说明: http://www.heavenlake.com/java2word/doc
免费下载:http://dev.heavenlake.com:81/developer/listthreads?forum=8

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值