用户登录
用户注册

分享至

java页面生成word文档 java生成word文档的问题

  • 作者: 墨梅72529213
  • 来源: 51数据库
  • 2020-04-21

Jacob解决Word文档的读写问题收藏

Jacob 是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁。使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。Jacob下载的地址为:

http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368

配置:

(1)将解压包中的jacob.dll(x86常用,x64)拷到jdk安装目录下的jre\bin文件夹或windows安装路径下的WINDOWS\system32文件夹下

(2)将jacob.jar文件拷到classpath下即可

常见问题解决:

对于”java.lang.UnsatisfiedLinkError: C:\WINDOWS\system32\jacob-1.14.3-x86.dll: 由于应用程序配置不正确,应用程序未能启动。重新安装应用程序可能会纠正”这个问题,可以通过

重新下载Jacob的jar及dll文件(最好版本比现在的低,如1.11)解决

实例制作(主要功能:标题制作,表格制作,合并表格,替换文本,页眉页脚,书签处理):

import com.jacob.activeX.ActiveXComponent;

import com.jacob.com.Dispatch;

import com.jacob.com.Variant;

public class WordOperate {

public static void main(String args[]) {

ActiveXComponent wordApp = new ActiveXComponent("Word.Application"); // 启动word

// Set the visible property as required.

Dispatch.put(wordApp, "Visible", new Variant(true));// //设置word可见

Dispatch docs = wordApp.getProperty("Documents").toDispatch();

// String inFile = "d:\\test.doc";

// Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method,

// new Object[] { inFile, new Variant(false), new Variant(false)},//参数3,false:可写,true:只读

// new int[1]).toDispatch();//打开文档

Dispatch document = Dispatch.call(docs, "Add").toDispatch();// create new document

String userName = wordApp.getPropertyAsString("Username");// 显示用户信息

System.out.println("用户名:" + userName);

// 文档对齐,字体设置////////////////////////

Dispatch selection = Dispatch.get(wordApp, "Selection").toDispatch();

Dispatch align = Dispatch.get(selection, "ParagraphFormat")

.toDispatch(); // 行列格式化需要的对象

Dispatch font = Dispatch.get(selection, "Font").toDispatch(); // 字型格式化需要的对象

// 标题处理////////////////////////

Dispatch.put(align, "Alignment", "1"); // 1:置中 2:靠右 3:靠左

Dispatch.put(font, "Bold", "1"); // 字型租体

Dispatch.put(font, "Color", "1,0,0,0"); // 字型颜色红色

Dispatch.call(selection, "TypeText", "Word文档处理"); // 写入标题内容

Dispatch.call(selection, "TypeParagraph"); // 空一行段落

Dispatch.put(align, "Alignment", "3"); // 1:置中 2:靠右 3:靠左

Dispatch.put(selection, "Text", " ");

Dispatch.call(selection, "MoveDown"); // 光标标往下一行

//表格处理////////////////////////

Dispatch tables = Dispatch.get(document, "Tables").toDispatch();

Dispatch range = Dispatch.get(selection, "Range").toDispatch();

Dispatch table1 = Dispatch.call(tables, "Add", range, new Variant(3),

new Variant(2), new Variant(1)).toDispatch(); // 设置行数,列数,表格外框宽度

// 所有表格

Variant tableAmount = Dispatch.get(tables, "count");

System.out.println(tableAmount);

// 要填充的表格

Dispatch t1 = Dispatch.call(tables, "Item", new Variant(1))

.toDispatch();

Dispatch t1_row = Dispatch.get(t1, "rows").toDispatch();// 所有行

int t1_rowNum = Dispatch.get(t1_row, "count").getInt();

Dispatch.call(Dispatch.get(t1, "columns").toDispatch(), "AutoFit");// 自动调整

int t1_colNum = Dispatch.get(Dispatch.get(t1, "columns").toDispatch(),

"count").getInt();

System.out.println(t1_rowNum + " " + t1_colNum);

for (int i = 1; i <= t1_rowNum; i++) {

for (int j = 1; j <= t1_colNum; j++) {

Dispatch cell = Dispatch.call(t1, "Cell", new Variant(i),

new Variant(j)).toDispatch();// 行,列

Dispatch.call(cell, "Select");

Dispatch.put(selection, "Text", "cell" + i + j); // 写入word的内容

Dispatch.put(font, "Bold", "0"); // 字型租体(1:租体 0:取消租体)

Dispatch.put(font, "Color", "1,1,1,0"); // 字型颜色

Dispatch.put(font, "Italic", "1"); // 斜体 1:斜体 0:取消斜体

Dispatch.put(font, "Underline", "1"); // 下划线

Dispatch Range = Dispatch.get(cell, "Range").toDispatch();

String cellContent = Dispatch.get(Range, "Text").toString();

System.out.println((cellContent.substring(0, cellContent

.length() - 1)).trim());

}

Dispatch.call(selection, "MoveDown"); // 光标往下一行(才不会输入盖过上一输入位置)

}

//合并单元格////////////////////////

Dispatch.put(selection, "Text", " ");

Dispatch.call(selection, "MoveDown"); // 光标标往下一行

Dispatch range2 = Dispatch.get(selection, "Range").toDispatch();

Dispatch table2 = Dispatch.call(tables, "Add", range2, new Variant(8),

new Variant(4), new Variant(1)).toDispatch(); // 设置行数,列数,表格外框宽度

Dispatch t2 = Dispatch.call(tables, "Item", new Variant(2))

.toDispatch();

Dispatch beginCell = Dispatch.call(t2, "Cell", new Variant(1),

new Variant(1)).toDispatch();

Dispatch endCell = Dispatch.call(t2, "Cell", new Variant(4),

new Variant(4)).toDispatch();

Dispatch.call(beginCell, "Merge", endCell);

for (int row = 1; row <= Dispatch.get(

Dispatch.get(t2, "rows").toDispatch(), "count").getInt(); row++) {

for (int col = 1; col <= Dispatch.get(

Dispatch.get(t2, "columns").toDispatch(), "count").getInt(); col++) {

if (row == 1) {

Dispatch cell = Dispatch.call(t2, "Cell", new Variant(1),

new Variant(1)).toDispatch();// 行,列

Dispatch.call(cell, "Select");

Dispatch.put(font, "Color", "1,1,1,0"); // 字型颜色

Dispatch.put(selection, "Text", "merge Cell!");

} else {

Dispatch cell = Dispatch.call(t2, "Cell", new Variant(row),

new Variant(col)).toDispatch();// 行,列

Dispatch.call(cell, "Select");

Dispatch.put(font, "Color", "1,1,1,0"); // 字型颜色

Dispatch.put(selection, "Text", "cell" + row + col);

}

}

Dispatch.call(selection, "MoveDown");

}

//Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));// 取消选择

// Object content = Dispatch.get(doc,"Content").toDispatch();

// Word文档内容查找及替换////////////////////////

Dispatch.call(selection, "TypeParagraph"); // 空一行段落

Dispatch.put(align, "Alignment", "3"); // 1:置中 2:靠右 3:靠左

Dispatch.put(font, "Color", 0);

Dispatch.put(selection, "Text", "欢迎,Hello,world!");

Dispatch.call(selection, "HomeKey", new Variant(6));// 移到开头

Dispatch find = Dispatch.call(selection, "Find").toDispatch();// 获得Find组件

Dispatch.put(find, "Text", "hello"); // 查找字符串"hello"

Dispatch.put(find, "Forward", "True");// 向前查找

// Dispatch.put(find, "Format", "True");// 设置格式

Dispatch.put(find, "MatchCase", "false");// 大小写匹配

Dispatch.put(find, "MatchWholeWord", "True"); // 全字匹配

Dispatch.call(find, "Execute"); // 执行查询

Dispatch.put(selection, "Text", "你好");// 替换为"你好"

//使用方法传入的参数parameter调用word文档中的MyWordMacro宏//

//Dispatch.call(document,macroName,parameter);

//Dispatch.invoke(document,macroName,Dispatch.Method,parameter,new int[1]);

//页眉,页脚处理////////////////////////

Dispatch ActiveWindow = wordApp.getProperty("ActiveWindow")

.toDispatch();

Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane")

.toDispatch();

Dispatch View = Dispatch.get(ActivePane, "View").toDispatch();

Dispatch.put(View, "SeekView", "9"); //9是设置页眉

Dispatch.put(align, "Alignment", "1"); // 置中

Dispatch.put(selection, "Text", "这里是页眉"); // 初始化时间

Dispatch.put(View, "SeekView", "10"); // 10是设置页脚

Dispatch.put(align, "Alignment", "2"); // 靠右

Dispatch.put(selection, "Text", "这里是页脚"); // 初始化从1开始

//书签处理(打开文档时处理)////////////////////////

//Dispatch activeDocument = wordApp.getProperty("ActiveDocument").toDispatch();

Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();

boolean isExist = Dispatch.call(bookMarks, "Exists", "bookMark1")

.getBoolean();

if (isExist == true) {

Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", "bookMark1")

.toDispatch();

Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();

Dispatch.put(range1, "Text", new Variant("当前是书签1的文本信息!"));

String bookMark1Value = Dispatch.get(range1, "Text").toString();

System.out.println(bookMark1Value);

} else {

System.out.println("当前书签不存在,重新建立!");

Dispatch.call(bookMarks, "Add", "bookMark1", selection);

Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", "bookMark1")

.toDispatch();

Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();

Dispatch.put(range1, "Text", new Variant("当前是书签1的文本信息!"));

String bookMark1Value = Dispatch.get(range1, "Text").toString();

System.out.println(bookMark1Value);

}

//保存操作////////////////////////

Dispatch.call(document, "SaveAs", "D:/wordOperate.doc");

//Dispatch.invoke((Dispatch) doc, "SaveAs", Dispatch.Method, new Object[]{htmlPath, new Variant(8)}, new int[1]); //生成html文件

// 0 = wdDoNotSaveChanges

// -1 = wdSaveChanges

// -2 = wdPromptToSaveChanges

//Dispatch.call(document, "Close", new Variant(0));

// // worddoc.olefunction("protect",2,true,"");

// // Dispatch bookMarks = wordApp.call(docs,"Bookmarks").toDispatch();

// // System.out.println("bookmarks"+bookMarks.getProgramId());

// //Dispatch.call(doc, "Save"); //保存

// // Dispatch.call(doc, "Close", new Variant(true));

// //wordApp.invoke("Quit",new Variant[]{});

// wordApp.safeRelease();//Finalizers call this method

}

}

java 代码生成word文件

没定格式的话可以再jsp页面添加这段:

<%

response.reset();

response.setContentType("application/vnd.ms-excel;charset=utf-8");

java.util.Date date = new Date();

DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");

String Starttime = df.format(date).toString();

response.setHeader("Content-disposition", "attachment; filename=GroupingInformation_"+ Starttime + ".doc");

%>

如果要定好格式的话,只有自己去看poi比较复杂。(但是用习惯了就没大问题了。)

poi后台:

导出第三句是格式,这个自己去试试。

我看网上说的poi对于word的支持不太好啊?不是很复杂的word文档,但是里面会有表格和一下描述文字

对了。。。poi后台我导出的Excel。。一般情况下用没定格式的导出word也行,怎么说呢,你加了那段话,系统就直接复制你的页面过去,所以你的页面是什么样子,基本导出就是什么样子的。。。当你跳转这个页面的时候就系统就会问你报存word文件否。。。。word导出,你的table也会出来。

java中如何将有图片的页面导出成Word文档

http://blog.163.com/ask_rent@yeah/blog/static/139893663201102471721745/

可以参考一下

如何把页面内容导出为word? (Java)

目前主要是OFFICE03和07,都支持打开HTML格式的文档的,这个方法应该可行.

另外OFFICE源码是不公开的,所以不可能纯靠自己程序生成DOC,还是要靠OFFICE

java导出word文档后,怎么在客户端提供下载。。。

服务器端生成然后将文件通过网络传递给客户端。

如果要制造客户端生成的假象就在传递完后服务器删除word文件。

服务器生成Word文件——>客户端与服务器建立通讯——>服务器发送文件给客户端

Java 生成Word文档,是跨平台的,如何实现

跨平台文档,不如生成HTML文件更好,word也可以打开,其他平台也能打开。

如果切实需要二进制文件,其它平台要打开的话,目前有永中office,openoffice.org,libreoffice。

永中office本身就是JAVA编写的,在java中可以调用生成word文件。

openoffice.org,libreoffice本身也与java有密切的渊源,跨平台与生成word都没问题。

你可以使用这些软件实现你的需求,不用你自己编写了。

当然,附带的问题就是你在相关的电脑里必须安装这些软件。

java如何生成word文档功能是怎么实现的

跨平台文档,不如生成HTML文件更好,word也可以打开,其他平台也能打开。 如果切实需要二进制文件,其它平台要打开的话,目前有永中office,openoffice.org,libreoffice。 永中office本身就是JAVA编写的,在java中可以调用生成word文件。

java如何根据word模板生成word文档

先下载jacob_1.10.1.zip。

解压后将jacob.dll放到windows/system32下面或\j2sdk\bin下面。

将jacob.jar加入项目。

/*

* Java2word.java

*

* Created on 2007年8月13日, 上午10:32

*

* To

change this template, choose Tools | Template Manager

* and open the template

in the editor.

*/

/*

* 传入数据为HashMap对象,对象中的Key代表word模板中要替换的字段,Value代表用来替换的值。

*

word模板中所有要替换的字段(即HashMap中的Key)以特殊字符开头和结尾,如:$code$、$date$……,

以免执行错误的替换。

*

所有要替换为图片的字段,Key中需包含image或者Value为图片的全路径(目前只判断文件后缀名为:.bmp、

.jpg、.gif)。

*

要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中:R代表从表格的第R行开始替换,N代表

word模板中的第N张表格;Value为ArrayList对象,ArrayList中包含的对象统一为String[],一条String[]代

表一行数据,ArrayList中第一条记录为特殊记录,记录的是表格中要替换的列号,如:要替换第一列、第三列、

第五列的数据,则第一条记录为String[3]

{“1”,”3”,”5”}。

*/

package com.word.util;

/**

*

* @author kdl

*/

import java.util.ArrayList;

import

java.util.HashMap;

import java.util.Iterator;

import com.jacob.activeX.ActiveXComponent;

import

com.jacob.com.Dispatch;

import com.jacob.com.Variant;

public class Java2word {

private boolean saveOnExit;

/**

* word文档

*/

Dispatch doc = null;

/**

* word运行程序对象s

*/

private ActiveXComponent

word;

/**

* 所有word文档

*/

private Dispatch

documents;

/**

* 构造函数

*/

public Java2word() {

if(word==null){

word = new

ActiveXComponent("Word.Application");

word.setProperty("Visible",new

Variant(false));

}

if(documents==null)

documents = word.getProperty("Documents").toDispatch();

saveOnExit =

false;

}

/**

* 设置参数:退出时是否保存

* @param

saveOnExit boolean true-退出时保存文件,false-退出时不保存文件

*/

public void

setSaveOnExit(boolean saveOnExit) {

this.saveOnExit =

saveOnExit;

}

/**

* 得到参数:退出时是否保存

* @return

boolean true-退出时保存文件,false-退出时不保存文件

*/

public boolean

getSaveOnExit() {

return saveOnExit;

}

/**

* 打开文件

* @param inputDoc String 要打开的文件,全路径

*

@return Dispatch 打开的文件

*/

public Dispatch open(String inputDoc)

{

return

Dispatch.call(documents,"Open",inputDoc).toDispatch();

//return

Dispatch.invoke(documents,"Open",Dispatch.Method,new Object[]{inputDoc},new

int[1]).toDispatch();

}

/**

* 选定内容

*

@return Dispatch 选定的范围或插入点

*/

public Dispatch select()

{

return word.getProperty("Selection").toDispatch();

}

/**

* 把选定内容或插入点向上移动

* @param selection

Dispatch 要移动的内容

* @param count int 移动的距离

*/

public

void moveUp(Dispatch selection,int count) {

for(int i = 0;i <

count;i ++)

Dispatch.call(selection,"MoveUp");

}

/**

* 把选定内容或插入点向下移动

* @param selection

Dispatch 要移动的内容

* @param count int 移动的距离

*/

public

void moveDown(Dispatch selection,int count) {

for(int i = 0;i <

count;i ++)

Dispatch.call(selection,"MoveDown");

}

/**

* 把选定内容或插入点向左移动

* @param selection

Dispatch 要移动的内容

* @param count int 移动的距离

*/

public

void moveLeft(Dispatch selection,int count) {

for(int i = 0;i <

count;i ++) {

Dispatch.call(selection,"MoveLeft");

}

}

/**

* 把选定内容或插入点向右移动

* @param

selection Dispatch 要移动的内容

* @param count int 移动的距离

*/

public void moveRight(Dispatch selection,int count) {

for(int i =

0;i < count;i ++)

Dispatch.call(selection,"MoveRight");

}

/**

*

把插入点移动到文件首位置

* @param selection Dispatch 插入点

*/

public

void moveStart(Dispatch selection) {

Dispatch.call(selection,"HomeKey",new Variant(6));

}

/**

* 从选定内容或插入点开始查找文本

* @param selection Dispatch

选定内容

* @param toFindText String 要查找的文本

* @return boolean

true-查找到并选中该文本,false-未查找到文本

*/

public boolean find(Dispatch

selection,String toFindText) {

//从selection所在位置开始查询

Dispatch find = word.call(selection,"Find").toDispatch();

//设置要查找的内容

Dispatch.put(find,"Text",toFindText);

//向前查找

Dispatch.put(find,"Forward","True");

//设置格式

Dispatch.put(find,"Format","True");

//大小写匹配

Dispatch.put(find,"MatchCase","True");

//全字匹配

Dispatch.put(find,"MatchWholeWord","True");

//查找并选中

return Dispatch.call(find,"Execute").getBoolean();

}

/**

* 把选定内容替换为设定文本

* @param selection

Dispatch 选定内容

* @param newText String 替换为文本

*/

public

void replace(Dispatch selection,String newText) {

//设置替换文本

Dispatch.put(selection,"Text",newText);

}

/**

* 全局替换

* @param selection Dispatch

选定内容或起始插入点

* @param oldText String 要替换的文本

* @param newText

String 替换为文本

*/

public void replaceAll(Dispatch

selection,String oldText,Object replaceObj) {

//移动到文件开头

moveStart(selection);

if(oldText.startsWith("table") ||

replaceObj instanceof ArrayList)

replaceTable(selection,oldText,(ArrayList) replaceObj);

else

{

String newText = (String) replaceObj;

if(newText==null)

newText="";

if(oldText.indexOf("image") != -1&!newText.trim().equals("") ||

newText.lastIndexOf(".bmp") != -1 || newText.lastIndexOf(".jpg") != -1 ||

newText.lastIndexOf(".gif") != -1){

while(find(selection,oldText)) {

replaceImage(selection,newText);

Dispatch.call(selection,"MoveRight");

}

}else{

while(find(selection,oldText))

{

replace(selection,newText);

Dispatch.call(selection,"MoveRight");

}

}

}

}

/**

* 替换图片

* @param

selection Dispatch 图片的插入点

* @param imagePath String 图片文件(全路径)

*/

public void replaceImage(Dispatch selection,String imagePath)

{

Dispatch.call(Dispatch.get(selection,"InLineShapes").toDispatch(),"AddPicture",imagePath);

}

/**

* 替换表格

* @param selection Dispatch

插入点

* @param tableName String

表格名称,形如table$1@1、table$2@1...table$R@N,R代表从表格中的第N行开始填充,N代表word文件中的第N张表

* @param fields HashMap 表格中要替换的字段与数据的对应表

*/

public void

replaceTable(Dispatch selection,String tableName,ArrayList dataList)

{

if(dataList.size() <= 1) {

System.out.println("Empty table!");

return;

}

//要填充的列

String[] cols = (String[])

dataList.get(0);

//表格序号

String tbIndex =

tableName.substring(tableName.lastIndexOf("@") + 1);

//从第几行开始填充

int fromRow =

Integer.parseInt(tableName.substring(tableName.lastIndexOf("$") +

1,tableName.lastIndexOf("@")));

//所有表格

Dispatch tables =

Dispatch.get(doc,"Tables").toDispatch();

//要填充的表格

Dispatch table = Dispatch.call(tables,"Item",new

Variant(tbIndex)).toDispatch();

//表格的所有行

Dispatch rows =

Dispatch.get(table,"Rows").toDispatch();

//填充表格

for(int

i = 1;i < dataList.size();i ++) {

//某一行数据

String[] datas = (String[]) dataList.get(i);

//在表格中添加一行

if(Dispatch.get(rows,"Count").getInt() < fromRow +

i - 1)

Dispatch.call(rows,"Add");

//填充该行的相关列

for(int j = 0;j < datas.length;j ++)

{

//得到单元格

Dispatch cell =

Dispatch.call(table,"Cell",Integer.toString(fromRow + i -

1),cols[j]).toDispatch();

//选中单元格

Dispatch.call(cell,"Select");

//设置格式

Dispatch font = Dispatch.get(selection,"Font").toDispatch();

Dispatch.put(font,"Bold","0");

Dispatch.put(font,"Italic","0");

//输入数据

Dispatch.put(selection,"Text",datas[j]);

}

}

}

/**

* 保存文件

* @param outputPath String

输出文件(包含路径)

*/

public void save(String outputPath) {

Dispatch.call(Dispatch.call(word,"WordBasic").getDispatch(),"FileSaveAs",outputPath);

}

/**

* 关闭文件

* @param document Dispatch

要关闭的文件

*/

public void close(Dispatch doc) {

Dispatch.call(doc,"Close",new Variant(saveOnExit));

word.invoke("Quit",new Variant[]{});

word = null;

}

/**

* 根据模板、数据生成word文件

* @param inputPath

String 模板文件(包含路径)

* @param outPath String 输出文件(包含路径)

* @param

data HashMap 数据包(包含要填充的字段、对应的数据)

*/

public void toWord(String

inputPath,String outPath,HashMap data) {

String oldText;

Object newValue;

try {

if(doc==null)

doc = open(inputPath);

Dispatch selection =

select();

Iterator keys =

data.keySet().iterator();

while(keys.hasNext())

{

oldText = (String) keys.next();

newValue = data.get(oldText);

replaceAll(selection,oldText,newValue);

}

save(outPath);

} catch(Exception

e) {

System.out.println("操作word文件失败!");

e.printStackTrace();

} finally {

if(doc !=

null)

close(doc);

}

}

转载请注明出处51数据库 » java页面生成word文档 java生成word文档的问题

软件
前端设计
程序设计
Java相关