本文主要是介绍0004-jacob操作word文档,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用场景:将后台数据做word文档保存,支持客户端下载
操作步骤:
1.首先制定word模板,制作格式如下:
编号:$id$ 发生时间:$occur_time$
2.后天调用jacob.ajr包,编写WordTemplate类
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
* jacob操作MSword类
*
* @author
*/
public class WordTemplate {
// word文档
private Dispatch doc;
// word运行程序对象
private ActiveXComponent word;
// 所有word文档集合
private Dispatch documents;
// 选定的范围或插入点
private Dispatch selection;
private boolean saveOnExit = true;
public WordTemplate() {
if (word == null) {
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(false)); // 不可见打开word
word.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
}
if (documents == null)
documents = word.getProperty("Documents").toDispatch();
}
/**
* 设置退出时参数
*
* @param saveOnExit
* boolean true-退出时保存文件,false-退出时不保存文件
*/
public void setSaveOnExit(boolean saveOnExit) {
this.saveOnExit = saveOnExit;
}
/**
* 创建一个新的word文档
*
*/
public void createNewDocument() {
doc = Dispatch.call(documents, "Add").toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
/**
* 打开一个已存在的文档
*
* @param docPath
*/
public void openDocument(String docPath) {
doc = Dispatch.call(documents, "Open", docPath).toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
/**
* 把插入点移动到文件首位置
*
*/
public void moveStart() {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
Dispatch.call(selection, "HomeKey", new Variant(6));
}
/**
* 从选定内容或插入点开始查找文本
*
* @param toFindText
* 要查找的文本
* @return boolean true-查找到并选中该文本,false-未查找到文本
*/
@SuppressWarnings("static-access")
public boolean find(String toFindText) {
if (toFindText == null || toFindText.equals(""))
return false;
// 从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 toFindText
* 查找字符串
* @param newText
* 要替换的内容
* @return
*/
public boolean replaceText(String toFindText, String newText) {
this.moveStart();
if (!find(toFindText))
return false;
Dispatch.put(selection, "Text", newText);
return true;
}
/**
* 文件保存或另存为
*
* @param savePath
* 保存或另存为路径
*/
public void save(String savePath) {
Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),
"FileSaveAs", savePath);
}
/**
* 关闭全部应用
*
*/
public void close() {
// closeDocument();
if (word != null) {
Dispatch.call(word, "Quit");
word = null;
}
selection = null;
documents = null;
}
public void openWord(boolean makeVisible) {
// 启动com的线程
ComThread.InitSTA();
// 打开word(如果word未开启时)
if (word == null) {
word = new ActiveXComponent("Word.Application");
}
// 设置word是可见或不可见(true:显示;false:不显示)
Dispatch.put(word, "Visible", new Variant(makeVisible));
}
}
3.在service实现替换,并通过流传递到前台
public void getWorkorderInfo(String id, HttpServletResponse response)
throws BusinessException {
// WordTemplate wordTemplate=new WordTemplate();
String string = this.getClass().getClassLoader().getResource("")
.getPath();
String s = string.substring(1);
String templetPath = s + "finish.doc"; // 模版文件
WordTemplate word2 = new WordTemplate();
//String templetPath = "d:\\finish.doc"; // 模版文件
String otPath = "d:/" + id + ".doc"; // 保存文件
try {
// 是否显示打开word
word2.openWord(false);
// 打开模版文件
word2.openDocument(templetPath);
WorkOrderInfo workOrderInfo = workOrderInfoMapper
.queryWorkOrderInfoDetail(id);
System.out.println(workOrderInfo.getDownTime());
List<WorkOrderLog> workOrderLogList = workOrderLogMapper
.queryWorkOrderLogById(id);
List<String> list = new ArrayList<String>();
String logmergeString = "";
for (int i = 0; i < workOrderLogList.size(); i++) {
logmergeString = workOrderLogList.get(i).getOperatorLog();
list.add(logmergeString);
}
workOrderInfo.setWorkOrderLog(list);
//映射的使用
Class clazz = workOrderInfo.getClass();
// 得打WorkOrderInfo的所有属性
Field[] fils = clazz.getDeclaredFields();
// Map<String,String> map = new HashMap<String,String>();
Method m2 = null;
for (int i = 0; i < fils.length; i++) {
System.out.println(fils[i].getName());
String name = fils[i].getName();
m2 = clazz.getDeclaredMethod("get"
+ name.substring(0, 1).toUpperCase()
+ name.substring(1));
word2.save(otPath);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// 关闭Word
word2.close();
try {
//这里需要特别注意,需要延迟一定时间,否则有可能在word2.close();还未关闭的时候,downloadDoc(response, otPath, id + ".doc");
//已经将该文件打开,在后面删除的时候,无法将word2.save(otPath);的word文档删除掉。
TimeUnit.SECONDS.sleep(1L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
downloadDoc(response, otPath, id + ".doc");
File file =new File(otPath);
if (file.isFile() && file.exists()) {
file.getAbsoluteFile().delete();
}
}
}
4.文件下载类
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
public class FileDownload {
/**
* @param response
* @param filePath//文件完整路径(包括文件名和扩展名)
* @param fileName//下载后看到的文件名
* @return 文件名
*/
public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{
byte[] data = FileUtil.toByteArray2(filePath);
fileName = URLEncoder.encode(fileName, "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/x-msdownload;charset=UTF-8");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
response.flushBuffer();
}
}
5.文件公共类
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
public class FileUtil {
/**
* 创建目录
*
* @param destDirName
* 目标目录名
* @return 目录创建成功返回true,否则返回false
*/
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
return false;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
// 创建单个目录
if (dir.mkdirs()) {
return true;
} else {
return false;
}
}
/**
* 删除文件
*
* @param filePathAndName
* String 文件路径及名称 如c:/fqf.txt
* @param fileContent
* String
* @return boolean
*/
public static void delFile(String filePathAndName) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
java.io.File myDelFile = new java.io.File(filePath);
myDelFile.delete();
} catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
/**
* 读取到字节数组0
*
* @param filePath //路径
* @throws IOException
*/
public static byte[] getContent(String filePath) throws IOException {
File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
System.out.println("file too big...");
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offset < buffer.length
&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
// 确保所有数据均被读取
if (offset != buffer.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
fi.close();
return buffer;
}
/**
* 读取到字节数组1
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] toByteArray(String filePath) throws IOException {
File f = new File(filePath);
if (!f.exists()) {
throw new FileNotFoundException(filePath);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
/**
* 读取到字节数组2
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] toByteArray2(String filePath) throws IOException {
File f = new File(filePath);
if (!f.exists()) {
throw new FileNotFoundException(filePath);
}
FileChannel channel = null;
FileInputStream fs = null;
try {
fs = new FileInputStream(f);
channel = fs.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// do nothing
// System.out.println("reading");
}
return byteBuffer.array();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
*
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray3(String filePath) throws IOException {
FileChannel fc = null;
RandomAccessFile rf = null;
try {
rf = new RandomAccessFile(filePath, "r");
fc = rf.getChannel();
MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
fc.size()).load();
//System.out.println(byteBuffer.isLoaded());
byte[] result = new byte[(int) fc.size()];
if (byteBuffer.remaining() > 0) {
// System.out.println("remain");
byteBuffer.get(result, 0, byteBuffer.remaining());
}
return result;
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
rf.close();
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
6.注意项
将jacob-1.17-M2-x64.dll、jacob-1.17-M2-x86.dll拷贝放到Java\jdk1.6.0_45\jre\bin下面,或若为32位系统放在C:\Windows\System32下;若为64位系统放C:\Windows\SysWOW64下,把jar包拷贝到相应目录下
通过maven导入的方法:
1.创建e:/wordapplier/文件夹,将下载好的文件放在该文件夹下面
2.在cmd命令中执行以下
mvn install:install-file -DgroupId=com.jacob -DartifactId=jacob -Dversion=1.17-M2 -Dfile=e:/wordapplier/jacob.jar -Dpackaging=jar -DgeneratePom=true
3.在pom.xml文件中配置
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.17-M2</version>
</dependency>
这篇关于0004-jacob操作word文档的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!