当前位置: 首页 > 常见问题 > Word文档

poi 生成word,java生成word文档

  • Word文档
  • 2023-08-13

poi 生成word?方式如下:1、首先比如有一篇文章的前边设置一个方向,如横向,然后后边都设置为纵向,这样可以先将插入点定位到纵向页面的结尾,2、当然也可以将所有内容全部圈起来,然后在应用于中选中所选文字进行更改,3、那么,poi 生成word?一起来了解一下吧。

java生成word文档

ZipFile docxFile = new ZipFile(new File("c:/3.docx"));

ZipEntry documentXML = docxFile.getEntry("word/document.xml");

InputStream documentXMLIS = docxFile.getInputStream(documentXML);

String s = "";

InputStreamReader reader = new InputStreamReader(documentXMLIS,"UTF-8");

BufferedReader br = new BufferedReader(reader);

String str = null;

while ((str = br.readLine()) != null) {

s = s+str;

}

s = s.replaceAll("${key}", "替换内容");

System.out.println(s);

reader.close();

br.close();

if(true){

//return;

}

//ZipEntry imgFile = docxFile.getEntry("word/media/image1.png");

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

InputStream documentXMLIS1 = docxFile.getInputStream(documentXML);

Document doc = dbf.newDocumentBuilder().parse(documentXMLIS1);

Element docElement = doc.getDocumentElement();

//assertEquals("w:document", docElement.getTagName());

Element bodyElement = (Element) docElement.getElementsByTagName(

"w:body").item(0);

//assertEquals("w:body", bodyElement.getTagName());

Element pElement = (Element) bodyElement.getElementsByTagName("w:p")

.item(0);

//assertEquals("w:p", pElement.getTagName());

Element rElement = (Element) pElement.getElementsByTagName("w:r"歼吵).item(

0);

//assertEquals("w:r", rElement.getTagName());

Element tElement = (Element) rElement.getElementsByTagName("w:t").item(

0);

/拿清/assertEquals("w:t", tElement.getTagName());

//assertEquals("这是第一个测试文档", tElement.getTextContent());

//tElement.setTextContent("这是第一氏敏侍个用Java写的测试文档");

Transformer t = TransformerFactory.newInstance().newTransformer();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

t.transform(new DOMSource(doc), new StreamResult(baos));

ZipOutputStream docxOutFile = new ZipOutputStream(new FileOutputStream(

"response.docx"));

Enumeration entriesIter = (Enumeration) docxFile

.entries();

while (entriesIter.hasMoreElements()) {

ZipEntry entry = entriesIter.nextElement();

System.out.println(entry.getName());

if (entry.getName().equals("word/document.xml")) {

byte[] data = baos.toByteArray();

docxOutFile.putNextEntry(new ZipEntry(entry.getName()));

byte[] datas = s.getBytes("UTF-8");

docxOutFile.write(datas, 0, datas.length);

//docxOutFile.write(data, 0, data.length);

docxOutFile.closeEntry();

} else if(entry.getName().equals("word/media/image1.png")){

InputStream incoming = new FileInputStream("c:/aaa.jpg");

byte[] data = new byte[incoming.available()];

int readCount = incoming.read(data, 0, data.length);

docxOutFile.putNextEntry(new ZipEntry(entry.getName()));

docxOutFile.write(data, 0, readCount);

docxOutFile.closeEntry();

}else {

InputStream incoming = docxFile.getInputStream(entry);

byte[] data = new byte[incoming.available()];

int readCount = incoming.read(data, 0, data.length);

docxOutFile.putNextEntry(new ZipEntry(entry.getName()));

docxOutFile.write(data, 0, readCount);

docxOutFile.closeEntry();

}

}

docxOutFile.close();

java word模板poi生成文件

试试激卜竖弊逗我这个

XWPFRun r1 = p.createRun();

r1.setText(text);

r1.setFontSize(16);

CTRPr rpr = r1.getCTR().isSetRPr() ? r1.getCTR().getRPr() : r1.getCTR().addNewRPr();

CTFonts fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();

fonts.setAscii("仿宋");

fonts.setEastAsia("仿宋明大");

fonts.setHAnsi("仿宋");

easypoi导出word表格

我最近搭穗也在学:仅有的一点资料

import java.io.*;

import java.util.*;

import org.apache.poi.poifs.filesystem.*;

import org.apache.poi.util.LittleEndian;

public class WordTest {

public WordTest() {

}

public static boolean writeWordFile(String path, String content) {

boolean w = false;

try {

// byte b[] = content.getBytes( "ISO-8859-1 "孙灶);

byte b[] = content.getBytes();

ByteArrayInputStream bais = new ByteArrayInputStream(b);

POIFSFileSystem fs = new POIFSFileSystem();

DirectoryEntry directory = fs.getRoot();

DocumentEntry de = directory.createDocument( "WordDocument ", bais);

FileOutputStream ostream = new FileOutputStream(path);

fs.writeFilesystem(ostream);

bais.close();

ostream.close();

} catch (IOException e) {

e.printStackTrace();

}

return w;

}

public static void main(String[] args){

boolean b = writeWordFile( "E://test.doc ", "hello ");

}

}

/*

public String extractText(InputStream in) throws IOException {

ArrayList text = new ArrayList();

POIFSFileSystem fsys = new POIFSFileSystem(in);

DocumentEntry headerProps = (DocumentEntry) fsys.getRoot().getEntry( "WordDocument ");

DocumentInputStream din = fsys.createDocumentInputStream( "则枝扮WordDocument ");

byte[] header = new byte[headerProps.getSize()];

din.read(header);

din.close();

// Prende le informazioni dall 'header del documento

int info = LittleEndian.getShort(header, 0xa);

boolean useTable1 = (info & 0x200) != 0;

//boolean useTable1 = true;

// Prende informazioni dalla piece table

int complexOffset = LittleEndian.getInt(header, 0x1a2);

//int complexOffset = LittleEndian.getInt(header);

String tableName = null;

if (useTable1) {

tableName = "1Table ";

} else {

tableName = "0Table ";

}

DocumentEntry table = (DocumentEntry) fsys.getRoot().getEntry(tableName);

byte[] tableStream = new byte[table.getSize()];

din = fsys.createDocumentInputStream(tableName);

din.read(tableStream);

din.close();

din = null;

fsys = null;

table = null;

headerProps = null;

int multiple = findText(tableStream, complexOffset, text);

poi word

rt java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class XwpfTUtil {

/衡蠢*String filePath = "/sta.docx";

InputStream is;

XWPFDocument doc;

Map params = new HashMap();

{

params.put("${name}", "xxx");

params.put("${sex}", "男");

params.put("${political}", "共青团员");

params.put("${place}", "sssss");

params.put("${classes}", "3102"码拦尘);

params.put("${id}", "213123123");

params.put("${qq}", "213123");

params.put("${tel}", "312313213");

params.put("${oldJob}", "sadasd");

params.put("${swap}", "是");

params.put("${first}", "asdasd");

params.put("${second}", "综迟禅合事务部");

params.put("${award}", "asda");

params.put("${achievement}", "完成科协网站的开发");

params.put("${advice}", "没有建议");

程序生成word文档

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

}

以上就是poi 生成word的全部内容,POI操作word模板并生成新的word - (jianshu.com)POI在读写 word docx 文件时是通过 XWPF 模块来进行的,其核心是XWPFDocument。一个XWPFDocument代表一个docx文档,其可以用来读docx文档,也可以用来写docx文档。

猜你喜欢