在最近的一个项目中需要将一段字符类型的文本存为word,html并要将word的内容保存在数据库中,于是就有了如下的一个工具类,希望能对碰到这样需求的朋友提供点帮助。
匆匆忙忙的就copy上来了,没有做一些删减,有一些多余的东西,有兴趣的朋友可以自行略去。我的注释相对比较清楚,可以按照自己的需求进行组合。
在操作word的地方使用了jacob(jacob_1.9),这个工具网上很容易找到,将jacob.dll放置系统Path中,直接放在system32下也可以,jacob.jar放置在classPath中。
代码如下:WordBridge.java
/**
* WordBridge.java
*/
package com.kela.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.kela.db.PoolingDataSource;
/**
* 说明: 对word的操作 <p>
*
* @author kela.kf@gmail.com
*/
public class WordBridge {
Log log = LogFactory.getLog("WordBridgt");
private ActiveXComponent MsWordApp = null;
private Dispatch document = null;
/**
* 打开word
* @param makeVisible, true显示word, false不显示word
*/
public void openWord(boolean makeVisible) {
if (MsWordApp == null) {
MsWordApp = new ActiveXComponent("Word.Application");
}
Dispatch.put(MsWordApp, "Visible", new Variant(makeVisible));
}
/**
* 创建新的文档
*
*/
public void createNewDocument() {
Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
document = Dispatch.call(documents, "Add").toDispatch();
}
/**
* 关闭文档
*/
public void closeDocument() {
// 0 = wdDoNotSaveChanges
// -1 = wdSaveChanges
// -2 = wdPromptToSaveChanges
Dispatch.call(document, "Close", new Variant(0));
document = null;
}
/**
* 关闭word
*
*/
public void closeWord() {
Dispatch.call(MsWordApp, "Quit");
MsWordApp = null;
document = null;
}
/**
* 插入文本
* @param textToInsert 文本内容
*/
public void insertText(String textToInsert) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", textToInsert);
}
/**
* 保存文件
* @param filename
*/
public void saveFileAs(String filename) {
Dispatch.call(document, "SaveAs", filename);
}
/**
* 将word转换成html
* @param htmlFilePath
*/
public void wordToHtml(String htmlFilePath) {
Dispatch.invoke(document,"SaveAs", Dispatch.Method, new Object[]{htmlFilePath,new Variant(8)}, new int[1]);
}
/**
* 保存word的同时,保存一个html
* @param text 需要保存的内容
* @param wordFilePath word的路径
* @param htmlFilePath html的路径
* @throws LTOAException
*/
public void wordAsDbOrToHtml(String text, String wordFilePath, String htmlFilePath) throws LTOAException {
try {
openWord(false);
createNewDocument();
insertText(text);
saveFileAs(wordFilePath);
wordToHtml(htmlFilePath);
} catch (Exception ex) {
log.error("错误 - 对word的操作发生错误");
log.error("原因 - " + ex.getMessage());
throw new LTOAException(LTOAException.ERR_UNKNOWN, "对word的操作发生错误("
+ this.getClass().getName() + ".wordAsDbOrToHtml())", ex);
} finally {
closeDocument();
closeWord();
}
}
/**
* 将word保存至数据库
* @param wordFilePath
* @param RecordID
* @throws LTOAException
*/
public void wordAsDatabase(String wordFilePath, String RecordID) throws LTOAException {
Connection conn = null;
PreparedStatement pstmt = null;
PoolingDataSource pool = null;
File file = null;
String sql = "";
try {
sql = " UPDATE Document_File SET FileBody = ? WHERE RecordID = ? ";
pool = new PoolingDataSource();
conn = pool.getConnection();
file = new File(wordFilePath);
InputStream is = new FileInputStream(file);
byte[] blobByte = new byte[is.available()];
is.read(blobByte);
is.close();
pstmt = conn.prepareStatement(sql);
pstmt.setBinaryStream(1,(new ByteArrayInputStream(blobByte)), blobByte.length);
pstmt.setString(2, RecordID);
pstmt.executeUpdate();
} catch (Exception ex) {
log.error("错误 - 表 Document_File 更新数据发生意外错误");
log.error("原因 - " + ex.getMessage());
throw new LTOAException(LTOAException.ERR_UNKNOWN,
"表Document_File插入数据发生意外错误("
+ this.getClass().getName() + ".wordAsDatabase())", ex);
} finally {
pool.closePrepStmt(pstmt);
pool.closeConnection(conn);
}
}
/**
* 得到一个唯一的编号
* @return 编号
*/
public String getRecordID() {
String sRecordID = "";
java.util.Date dt=new java.util.Date();
long lg=dt.getTime();
Long ld=new Long(lg);
sRecordID =ld.toString();
return sRecordID;
}
/**
* 得到保存word和html需要的路径
* @param systemType 模块类型 givInfo, sw, fw
* @param fileType 文件类型 doc, html
* @param recID 文件编号
* @return 路径
*/
public String getWordFilePath(String systemType, String fileType, String recID) {
String filePath = "";
File file = new File(this.getClass().getResource("/").getPath());
filePath = file.getPath().substring(0, file.getPath().length() - 15);
if(systemType.equalsIgnoreCase("govInfo")) {
if(fileType.equalsIgnoreCase("doc"))
filePath = filePath + "/uploadFiles/govInfo/document/" + recID + ".doc";
else if(fileType.equalsIgnoreCase("htm"))
filePath = filePath + "/HTML/govInfo/" + recID + ".htm";
} else if(systemType.equalsIgnoreCase("sw")){
if(fileType.equalsIgnoreCase("doc"))
filePath = filePath + "/uploadFiles/sw/document/" + recID + ".doc";
else if(fileType.equalsIgnoreCase("htm"))
filePath = filePath + "/HTML/sw/" + recID + ".htm";
} else if(systemType.equalsIgnoreCase("fw")) {
if(fileType.equalsIgnoreCase("doc"))
filePath = filePath + "/uploadFiles/fw/document/" + recID + ".doc";
else if(fileType.equalsIgnoreCase("htm"))
filePath = filePath + "/HTML/fw/" + recID + ".htm";
}
return filePath;
}
}
匆匆忙忙的就copy上来了,没有做一些删减,有一些多余的东西,有兴趣的朋友可以自行略去。我的注释相对比较清楚,可以按照自己的需求进行组合。
在操作word的地方使用了jacob(jacob_1.9),这个工具网上很容易找到,将jacob.dll放置系统Path中,直接放在system32下也可以,jacob.jar放置在classPath中。
代码如下:WordBridge.java
/**
* WordBridge.java
*/
package com.kela.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.kela.db.PoolingDataSource;
/**
* 说明: 对word的操作 <p>
*
* @author kela.kf@gmail.com
*/
public class WordBridge {
Log log = LogFactory.getLog("WordBridgt");
private ActiveXComponent MsWordApp = null;
private Dispatch document = null;
/**
* 打开word
* @param makeVisible, true显示word, false不显示word
*/
public void openWord(boolean makeVisible) {
if (MsWordApp == null) {
MsWordApp = new ActiveXComponent("Word.Application");
}
Dispatch.put(MsWordApp, "Visible", new Variant(makeVisible));
}
/**
* 创建新的文档
*
*/
public void createNewDocument() {
Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
document = Dispatch.call(documents, "Add").toDispatch();
}
/**
* 关闭文档
*/
public void closeDocument() {
// 0 = wdDoNotSaveChanges
// -1 = wdSaveChanges
// -2 = wdPromptToSaveChanges
Dispatch.call(document, "Close", new Variant(0));
document = null;
}
/**
* 关闭word
*
*/
public void closeWord() {
Dispatch.call(MsWordApp, "Quit");
MsWordApp = null;
document = null;
}
/**
* 插入文本
* @param textToInsert 文本内容
*/
public void insertText(String textToInsert) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", textToInsert);
}
/**
* 保存文件
* @param filename
*/
public void saveFileAs(String filename) {
Dispatch.call(document, "SaveAs", filename);
}
/**
* 将word转换成html
* @param htmlFilePath
*/
public void wordToHtml(String htmlFilePath) {
Dispatch.invoke(document,"SaveAs", Dispatch.Method, new Object[]{htmlFilePath,new Variant(8)}, new int[1]);
}
/**
* 保存word的同时,保存一个html
* @param text 需要保存的内容
* @param wordFilePath word的路径
* @param htmlFilePath html的路径
* @throws LTOAException
*/
public void wordAsDbOrToHtml(String text, String wordFilePath, String htmlFilePath) throws LTOAException {
try {
openWord(false);
createNewDocument();
insertText(text);
saveFileAs(wordFilePath);
wordToHtml(htmlFilePath);
} catch (Exception ex) {
log.error("错误 - 对word的操作发生错误");
log.error("原因 - " + ex.getMessage());
throw new LTOAException(LTOAException.ERR_UNKNOWN, "对word的操作发生错误("
+ this.getClass().getName() + ".wordAsDbOrToHtml())", ex);
} finally {
closeDocument();
closeWord();
}
}
/**
* 将word保存至数据库
* @param wordFilePath
* @param RecordID
* @throws LTOAException
*/
public void wordAsDatabase(String wordFilePath, String RecordID) throws LTOAException {
Connection conn = null;
PreparedStatement pstmt = null;
PoolingDataSource pool = null;
File file = null;
String sql = "";
try {
sql = " UPDATE Document_File SET FileBody = ? WHERE RecordID = ? ";
pool = new PoolingDataSource();
conn = pool.getConnection();
file = new File(wordFilePath);
InputStream is = new FileInputStream(file);
byte[] blobByte = new byte[is.available()];
is.read(blobByte);
is.close();
pstmt = conn.prepareStatement(sql);
pstmt.setBinaryStream(1,(new ByteArrayInputStream(blobByte)), blobByte.length);
pstmt.setString(2, RecordID);
pstmt.executeUpdate();
} catch (Exception ex) {
log.error("错误 - 表 Document_File 更新数据发生意外错误");
log.error("原因 - " + ex.getMessage());
throw new LTOAException(LTOAException.ERR_UNKNOWN,
"表Document_File插入数据发生意外错误("
+ this.getClass().getName() + ".wordAsDatabase())", ex);
} finally {
pool.closePrepStmt(pstmt);
pool.closeConnection(conn);
}
}
/**
* 得到一个唯一的编号
* @return 编号
*/
public String getRecordID() {
String sRecordID = "";
java.util.Date dt=new java.util.Date();
long lg=dt.getTime();
Long ld=new Long(lg);
sRecordID =ld.toString();
return sRecordID;
}
/**
* 得到保存word和html需要的路径
* @param systemType 模块类型 givInfo, sw, fw
* @param fileType 文件类型 doc, html
* @param recID 文件编号
* @return 路径
*/
public String getWordFilePath(String systemType, String fileType, String recID) {
String filePath = "";
File file = new File(this.getClass().getResource("/").getPath());
filePath = file.getPath().substring(0, file.getPath().length() - 15);
if(systemType.equalsIgnoreCase("govInfo")) {
if(fileType.equalsIgnoreCase("doc"))
filePath = filePath + "/uploadFiles/govInfo/document/" + recID + ".doc";
else if(fileType.equalsIgnoreCase("htm"))
filePath = filePath + "/HTML/govInfo/" + recID + ".htm";
} else if(systemType.equalsIgnoreCase("sw")){
if(fileType.equalsIgnoreCase("doc"))
filePath = filePath + "/uploadFiles/sw/document/" + recID + ".doc";
else if(fileType.equalsIgnoreCase("htm"))
filePath = filePath + "/HTML/sw/" + recID + ".htm";
} else if(systemType.equalsIgnoreCase("fw")) {
if(fileType.equalsIgnoreCase("doc"))
filePath = filePath + "/uploadFiles/fw/document/" + recID + ".doc";
else if(fileType.equalsIgnoreCase("htm"))
filePath = filePath + "/HTML/fw/" + recID + ".htm";
}
return filePath;
}
}
发表评论
-
MyBatis的动态SQL详解
2012-08-19 20:44 713MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我 ... -
spring-动态装配bean
2012-03-19 20:04 916http://uu011.iteye.com/admin/bl ... -
XSocket的学习和总结(一)
2012-03-14 14:20 704http://blog.csdn.net/lizhi20040 ... -
xsocket基础学习一
2012-03-14 09:55 11181、这个开源的框架只需要有一个J2SE5.0就行了不需要其他的 ... -
io与nio的区别
2012-03-14 09:52 810io:提供读写操作 nio提供读写操作,基本单位为byteB ... -
详解FreeMarker生成复杂Word文档
2012-03-03 11:57 916http://www.java.sh/web/freemark ... -
Jacob解决Word文档的读写问题
2012-03-03 11:19 1080转于:北极之光的博客 标签:jacob word com 表格 ... -
Jacob解析word
2012-03-03 11:17 801由于项目需要,取得word的内容,因研究了下Jacob,尽管P ... -
Java服务器端List对象转换为JSON对象并返回客户端实例
2011-04-26 01:53 814http://apps.hi.baidu.com/share/ ... -
如何将tomcat启动注册为系统服务
2011-04-06 04:02 895曾经做过J2EE开发的朋友,一定对Tomcat这个东西最熟 ... -
添加tomcat 服务删除
2011-04-06 03:15 1310tomcat服务删除 关键字: tomcat服务删除 命令行 ... -
如何用Java操作Word, Excel, PDF文档
2011-04-05 03:27 727http://java.ccidnet.com/art/353 ... -
javascript 关闭
2011-03-31 10:32 0http://www.abab123.com/bbs/down ... -
定数显示通知
2011-03-30 11:56 0window.setInterval('shows()',10 ... -
两个LIST比对筛选返回LIST比对结果(转)
2011-03-28 11:09 1269两个LIST比对筛选返回LIST比对结果 不知道大家有没有碰到 ... -
map 转换Set遍历
2011-03-28 10:25 931Map map=new HashMap(); map.put( ... -
java实现mysql 数据库备份
2011-03-21 16:55 1111//db数据库 //ip 备份数据库地址 //user用户名 ...
相关推荐
JAVA根据数据库表生成word表格文档
java 动态获取数据库信息生成word(含表格,柱状图),并下载
java调用PageOffice读取数据库中的数据填充到word模板中,动态生成word文件
java生成word的实例 java导出Word文档的实例 项目说明
2.通过读取数据库更改原始的.doc文件、读取数据库生成pdf。 -然后更改webRoot下面的.doc文件。然后调用ReadWriteAndDownloadDocAction生成一 个新的word。 -读取数据库文件生成pdf调用createDBPdf类。 ...
利用JSF框架,在NETBEANS6.1开发环境中,构建出了一个...以该系统为蓝本,具体给出了Java语言读取Word模板文件的实现方法;利用MySQL数据库中的数据填充Word模板动态输出数据的实现方法及JSP提供Word文件下载的基本方法等。
本文档详细说明了java调用ireport环境搭建及数据库配置等,及java怎么调用ireport生成报告,附带java生成的报告代码只是word的,生成excel或者PDF可以修改方法即可。内容包含数据库连接配置,参数设置。
该代码可以通过运行main函数自动生成表结构包括表名字段和注释,现在生成的是txt版本后期会跟改成生成word或者Excel格式,请持续关注
Springboot Controller中使用service调SQL语句的方法,动态获取数据库信息添加到WORD表格中,检查到的数据绘制为柱形图(直方图)添加到文档中,并生成word(含表格,柱状图)存储到本地,在浏览器下载本地的word文档
数据库表结构生成WORD文档工具,亲测可用,另外可以生成PDF,大家下载试试看吧!
1、新增通过自定义模板生成Word文档的功能,可以使用FreeMarker模板生成自定义格式的数据库文档。 2、新增 Swagger2 在线API转离线API文档的功能,生成Word接口文档。 3、新增对 MariaDB 数据库的支持,需要删除旧的...
从mysql数据库导数据生成数据库word文档 软件架构 软件架构说明 springboot + mybatis 使用说明 修改application.properties里面数据库连接配置,配置生成的文件地址,数据库名 生成数据库下所有表文档 1)启动...
1.增加了对excel文件的支持,可以同时生成word 和excel文件 2.运行方式DocMain.java ExcelMain.java 3.生成excel文件的模板需要特别注意:xls模板中行数必须足够大,eg.ss:ExpandedRowCount="24000",否则生成的...
1.用的时候只要把jdbc.properties文件里的数据库配置改一下就可以了 2.要生成word文档就执行DocMain 3.要生成excel文档就执行ExcelMain
最近在做一个出卷系统,需要通过试卷模板从数据库中抽取题目,然后按照模板的样式生成完整的试卷,包括试卷格式的排版和图片的写入。这是用docx4j生成word文档。里面包括完整代码和所需jar包。
mysql字典表导出到word文件工具,修改配置文件后运行jar即可
代码是一个 eclipse + myeclipse 工程 最简单的JAVA操作读取excel java生成excel java读取word java连接SQL server数据库 还有一个简单的Java servlet的程序
html渲染页面转换为pdf并设置页眉,页码,水印,目录,二维码
支持导出MySQL数据库表结构!! 运行环境:jdk8+,需要Java运行环境 执行命令:java -jar data_to_word-1.0-SNAPSHOT.jar
Word从2003开始支持XML格式,用XML+Freemarder还做就很简单了,大致的思路是先用office2003或者2007编辑好 word的样式,然后另存为xml,将xml翻译为FreeMarker模板,最后用java来解析FreeMarker模板并输出Doc。...