java创建word代码 java怎么创建web项目

java 自动生成word怎么生成用java生成word文档
poi是apachejava创建word代码的一个项目,不过就算用poi你可能都觉得很烦,不过不要紧,这里提供java创建word代码了更加简单的一个接口给你java创建word代码:
这个包就是:tm-extractors-0.4.jar
下载之后,放到你的classpath就可以java创建word代码了,下面是如何使用它的一个例子:
【java创建word代码 java怎么创建web项目】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);
}
}
Java怎么操作OpenOffice创建word文档并向其设置内容将Word转Html的原理是这样的:
1、客户上传Word文档到服务器
2、服务器调用OpenOffice程序打开上传的Word文档
3、OpenOffice将Word文档另存为Html格式
4、Over
至此可见,这要求服务器端安装OpenOffice软件,其实也可以是MS Office,不过OpenOffice的优势是跨平台 , 你懂的 。恩,说明一下,本文的测试基于 MS Win7 Ultimate X64 系统 。
下面就是规规矩矩的实现 。
1、下载OpenOffice,
2、下载Jodconverter这是一个开启OpenOffice进行格式转化的第三方jar包 。
3、泡杯热茶,等待下载 。
4、安装OpenOffice,安装结束后,调用cmd,启动OpenOffice的一项服务:C:\Program Files (x86)\OpenOffice.org 3\programsoffice -headless -accept="socket,port=8100;urp;"
5、打开eclipse
6、喝杯热茶,等待eclipse打开 。
7、新建eclipse项目 , 导入Jodconverter/lib 下得jar包 。
* commons-io
* jodconverter
* juh
* jurt
* ridl
* slf4j-api
* slf4j-jdk14
* unoil
* xstream
8、Coding...
查看代码
package com.mzule.doc2html.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
/**
* 将Word文档转换成html字符串的工具类
*
* @author MZULE
*
*/
public class Doc2Html {
public static void main(String[] args) {
System.out
.println(toHtmlString(new File("C:/test/test.doc"), "C:/test"));
}
/**
* 将word文档转换成html文档
*
* @param docFile
*需要转换的word文档
* @param filepath
*转换之后html的存放路径
* @return 转换之后的html文件
*/
public static File convert(File docFile, String filepath) {
// 创建保存html的文件
File htmlFile = new File(filepath"/"new Date().getTime()
".html");
// 创建Openoffice连接
OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
try {
// 连接
con.connect();
} catch (ConnectException e) {
System.out.println("获取OpenOffice连接失败...");
e.printStackTrace();
}
// 创建转换器
DocumentConverter converter = new OpenOfficeDocumentConverter(con);
// 转换文档问html
converter.convert(docFile, htmlFile);
// 关闭openoffice连接
con.disconnect();
return htmlFile;
}
/**
* 将word转换成html文件,并且获取html文件代码 。
*
* @param docFile
*需要转换的文档
* @param filepath
*文档中图片的保存位置
* @return 转换成功的html代码
*/
public static String toHtmlString(File docFile, String filepath) {
// 转换word文档
File htmlFile = convert(docFile, filepath);
// 获取html文件流
StringBuffer htmlSb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(htmlFile)));
while (br.ready()) {
htmlSb.append(br.readLine());
}
br.close();
// 删除临时文件
htmlFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// HTML文件字符串
String htmlStr = htmlSb.toString();
// 返回经过清洁的html文本
return clearFormat(htmlStr, filepath);
}
/**
* 清除一些不需要的html标记
*
* @param htmlStr
*带有复杂html标记的html语句
* @return 去除了不需要html标记的语句
*/
protected static String clearFormat(String htmlStr, String docImgPath) {
// 获取body内容的正则
String bodyReg = "BODY .*/BODY";
Pattern bodyPattern = Pattern.compile(bodyReg);
Matcher bodyMatcher = bodyPattern.matcher(htmlStr);
if (bodyMatcher.find()) {
// 获取BODY内容,并转化BODY标签为DIV
htmlStr = bodyMatcher.group().replaceFirst("BODY", "DIV")
.replaceAll("/BODY", "/DIV");
}
// 调整图片地址
htmlStr = htmlStr.replaceAll("IMG SRC=https://www.04ip.com/"", "IMG SRC=https://www.04ip.com/""docImgPath
"/");
// 把P/P转换成/div/div保留样式
// content = content.replaceAll("(P)([^]*.*?)(\\/P)",
// "div$2/div");
// 把P/P转换成/div/div并删除样式
htmlStr = htmlStr.replaceAll("(P)([^]*)(.*?)(\\/P)", "p$3/p");
// 删除不需要的标签
htmlStr = htmlStr
.replaceAll(
"[/]?(font|FONT|span|SPAN|xml|XML|del|DEL|ins|INS|meta|META|[ovwxpOVWXP]:\\w )[^]*?",
"");
// 删除不需要的属性
htmlStr = htmlStr
.replaceAll(
"([^]*)(?:lang|LANG|class|CLASS|style|STYLE|size|SIZE|face|FACE|[ovwxpOVWXP]:\\w )=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^] )([^]*)",
"$1$2");
return htmlStr;
}
}
java生成word文档的问题Jacob解决Word文档的读写问题收藏
Jacob 是Java-COM Bridge的缩写java创建word代码 , 它在Java与微软的COM组件之间构建一座桥梁 。使用Jacob自带的DLL动态链接库java创建word代码,并通过JNI的方式实现了在Java平台上对COM程序的调用 。Jacob下载的地址为:
;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"ij); // 写入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"rowcol);
}
}
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 = https://www.04ip.com/post/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 = https://www.04ip.com/post/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如果电脑里装的有WORD , 可以通过JS新建一个WORD,并把页面文件拷贝进去 。
我这有操作Excel的,word的差不多 。
input type="button" onclick="javascript:method1('tableExcel');" value="https://www.04ip.com/post/导入到EXCEL"
SCRIPT LANGUAGE="javascript"
function method1(tableid) {//整个表格拷贝到EXCEL中
var curTbl = document.getElementById(tableid);
var oXL = new ActiveXObject("Excel.Application");
//创建AX对象excel
var oWB = oXL.Workbooks.Add();
//获取workbook对象
var oSheet = oWB.ActiveSheet;
//激活当前sheet
var sel = document.body.createTextRange();
sel.moveToElementText(curTbl);
//把表格中的内容移到TextRange中
sel.select();
//全选TextRange中内容
sel.execCommand("Copy");
//复制TextRange中内容
oSheet.Paste();
//粘贴到活动的EXCEL中
oXL.Visible = true;
//设置excel可见属性
}
function method2(tableid) //读取表格中每个单元到EXCEL中
{
var curTbl = document.getElementById(tableid);
var oXL = new ActiveXObject("Excel.Application");
//创建AX对象excel
var oWB = oXL.Workbooks.Add();
//获取workbook对象
var oSheet = oWB.ActiveSheet;
//激活当前sheet
var Lenr = curTbl.rows.length;
//取得表格行数
for (i = 0; iLenr; i)
{
var Lenc = curTbl.rows(i).cells.length;
//取得每行的列数
for (j = 0; jLenc; j)
{
oSheet.Cells(i1, j1).value = https://www.04ip.com/post/curTbl.rows(i).cells(j).innerText;
//赋值
}
}
oXL.Visible = true;
//设置excel可见属性
}
function getXlsFromTbl(inTblId, inWindow) {
try {
var allStr = "";
var curStr = "";
//alert("getXlsFromTbl");
if (inTblId != nullinTblId != ""inTblId != "null") {
curStr = getTblData(inTblId, inWindow);
}
if (curStr != null) {
allStr= curStr;
}
else {
alert("你要导出的表不存在!");
return;
}
var fileName = getExcelFileName();
doFileExport(fileName, allStr);
}
catch(e) {
alert("导出发生异常:"e.name"-"e.description"!");
}
}
function getTblData(inTbl, inWindow) {
var rows = 0;
//alert("getTblData is "inWindow);
var tblDocument = document;
if (!!inWindowinWindow != "") {
if (!document.all(inWindow)) {
return null;
}
else {
tblDocument = eval(inWindow).document;
}
}
var curTbl = tblDocument.getElementById(inTbl);
var outStr = "";
if (curTbl != null) {
for (var j = 0; jcurTbl.rows.length; j) {
//alert("j is "j);
for (var i = 0; icurTbl.rows[j].cells.length; i) {
//alert("i is "i);
if (i == 0rows0) {
outStr= " \t";
rows -= 1;
}
outStr= curTbl.rows[j].cells[i].innerText"\t";
if (curTbl.rows[j].cells[i].colSpan1) {
for (var k = 0; kcurTbl.rows[j].cells[i].colSpan - 1; k) {
outStr= " \t";
}
}
if (i == 0) {
if (rows == 0curTbl.rows[j].cells[i].rowSpan1) {
rows = curTbl.rows[j].cells[i].rowSpan - 1;
}
}
}
outStr= "\r\n";
}
}
else {
outStr = null;
alert(inTbl"不存在!");
}
return outStr;
}
function getExcelFileName() {
var d = new Date();
var curYear = d.getYear();
var curMonth = ""(d.getMonth()1);
var curDate = ""d.getDate();
var curHour = ""d.getHours();
var curMinute = ""d.getMinutes();
var curSecond = ""d.getSeconds();
if (curMonth.length == 1) {
curMonth = "0"curMonth;
}
if (curDate.length == 1) {
curDate = "0"curDate;
}
if (curHour.length == 1) {
curHour = "0"curHour;
}
if (curMinute.length == 1) {
curMinute = "0"curMinute;
}
if (curSecond.length == 1) {
curSecond = "0"curSecond;
}
var fileName = "leo_zhang""_"curYearcurMonthcurDate"_"curHourcurMinutecurSecond".csv";
//alert(fileName);
return fileName;
}
function doFileExport(inName, inStr) {
var xlsWin = null;
if (!!document.all("glbHideFrm")) {
xlsWin = glbHideFrm;
}
else {
var width = 6;
var height = 4;
var openPara = "left="(window.screen.width / 2 - width / 2)
",top="(window.screen.height / 2 - height / 2)
",scrollbars=no,width="width",height="height;
xlsWin = window.open("", "_blank", openPara);
}
xlsWin.document.write(inStr);
xlsWin.document.close();
xlsWin.document.execCommand('Saveas', true, inName);
xlsWin.close();
}
/SCRIPT
用java代码把内容写到Word文档?import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Test {
public static void main(String[] args) {
try
{
FileInputStream fr=new FileInputStream("test/123.txt");
InputStreamReader af=new InputStreamReader(fr);
BufferedReader bf=new BufferedReader(af);
FileOutputStream fo=new FileOutputStream("test/456.doc");
OutputStreamWriter osw=new OutputStreamWriter(fo);
BufferedWriter bw=new BufferedWriter(osw);
String line=bf.readLine();
while(line!=null)
{
System.out.println(line);
bw.write(line);
bw.newLine();
bw.flush();
line=bf.readLine();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
test/123.txt里的内容写到test/456.doc下了,在你的java src中建一个test文件夹 , 这里是相对路径
关于java创建word代码和java怎么创建web项目的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读