代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
Js
】
POI操作word2007(docx)文件的文本和图片
作者:
博超
/ 发布于
2016/4/6
/
1401
OI3.7+JAVA+word2007 POI后续版本中addPicture方法有改动导致不兼容 请注意
import java.io.IOException; import java.io.InputStream; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlToken; import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; /** * 自定义 XWPFDocument,并重写 createPicture()方法 */ public class CustomXWPFDocument extends XWPFDocument { public CustomXWPFDocument(InputStream in) throws IOException { super(in); } public CustomXWPFDocument() { super(); } public CustomXWPFDocument(OPCPackage pkg) throws IOException { super(pkg); } /** * @param id * @param width 宽 * @param height 高 * @param paragraph 段落 */ public void createPicture(int id, int width, int height,XWPFParagraph paragraph) { final int EMU = 9525; width *= EMU; height *= EMU; String blipId = getAllPictures().get(id).getPackageRelationship().getId(); CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline(); String picXml = "" + "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" + " <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" + " <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" + " <pic:nvPicPr>" + " <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" + " <pic:cNvPicPr/>" + " </pic:nvPicPr>" + " <pic:blipFill>" + " <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" + " <a:stretch>" + " <a:fillRect/>" + " </a:stretch>" + " </pic:blipFill>" + " <pic:spPr>" + " <a:xfrm>" + " <a:off x=\"0\" y=\"0\"/>" + " <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" + " </a:xfrm>" + " <a:prstGeom prst=\"rect\">" + " <a:avLst/>" + " </a:prstGeom>" + " </pic:spPr>" + " </pic:pic>" + " </a:graphicData>" + "</a:graphic>"; inline.addNewGraphic().addNewGraphicData(); XmlToken xmlToken = null; try { xmlToken = XmlToken.Factory.parse(picXml); } catch (XmlException xe) { xe.printStackTrace(); } inline.set(xmlToken); inline.setDistT(0); inline.setDistB(0); inline.setDistL(0); inline.setDistR(0); CTPositiveSize2D extent = inline.addNewExtent(); extent.setCx(width); extent.setCy(height); CTNonVisualDrawingProps docPr = inline.addNewDocPr(); docPr.setId(id); docPr.setName("图片" + id); docPr.setDescr("测试"); } } import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.HashMap; import java.util.Map; public class Test { public static void main(String[] args) throws Exception { Map<String, Object> param = new HashMap<String, Object>(); Map<String,Object> header = new HashMap<String, Object>(); header.put("width", 400); header.put("height", 150); header.put("type", "jpg"); header.put("content", WordUtil.inputStream2ByteArray(new FileInputStream("C:\\new.jpg"), true)); param.put("${img1}",header); Map<String,Object> header2 = new HashMap<String, Object>(); header2.put("width", 400); header2.put("height", 150); header2.put("type", "jpg"); header2.put("content", WordUtil.inputStream2ByteArray(new FileInputStream("C:\\new.jpg"), true)); param.put("${img2}",header2); param.put("${table1}", "1"); param.put("${table2}", "2"); param.put("${table5}", "5"); param.put("${table3}", "3"); param.put("${param1}", "oschina1"); param.put("${param53}", "oschina53"); CustomXWPFDocument doc = WordUtil.generateWord(param, "C:\\Users\\James\\Desktop\\docmodelreplaced333.docx"); FileOutputStream fopts = new FileOutputStream("C:\\Users\\James\\Desktop\\docmodelreplaced2.docx"); doc.write(fopts); fopts.close(); } } import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.poi.POIXMLDocument; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableRow; public class WordUtil { /** * 根据指定的参数值、模板,生成 word 文档 * @param param 需要替换的变量 * @param template 模板 */ public static CustomXWPFDocument generateWord(Map<String, Object> param, String template) { CustomXWPFDocument doc = null; try { OPCPackage pack = POIXMLDocument.openPackage(template); doc = new CustomXWPFDocument(pack); if (param != null && param.size() > 0) { //处理段落 List<XWPFParagraph> paragraphList = doc.getParagraphs(); processParagraphs(paragraphList, param, doc); //处理表格 Iterator<XWPFTable> it = doc.getTablesIterator(); while (it.hasNext()) { XWPFTable table = it.next(); List<XWPFTableRow> rows = table.getRows(); for (XWPFTableRow row : rows) { List<XWPFTableCell> cells = row.getTableCells(); for (XWPFTableCell cell : cells) { List<XWPFParagraph> paragraphListTable = cell.getParagraphs(); processParagraphs(paragraphListTable, param, doc); } } } } } catch (Exception e) { e.printStackTrace(); } return doc; } /** * 处理段落 * @param paragraphList */ public static void processParagraphs(List<XWPFParagraph> paragraphList,Map<String, Object> param,CustomXWPFDocument doc){ if(paragraphList != null && paragraphList.size() > 0){ for(XWPFParagraph paragraph:paragraphList){ List<XWPFRun> runs = paragraph.getRuns(); for (XWPFRun run : runs) { String text = run.getText(0); if(text != null){ boolean isSetText = false; for (Entry<String, Object> entry : param.entrySet()) { String key = entry.getKey(); if(text.indexOf(key) != -1){ isSetText = true; Object value = entry.getValue(); if (value instanceof String) {//文本替换 text = text.replace(key, value.toString()); System.out.println(text); } else if (value instanceof Map) {//图片替换 text = text.replace(key, ""); Map pic = (Map)value; int width = Integer.parseInt(pic.get("width").toString()); int height = Integer.parseInt(pic.get("height").toString()); int picType = getPictureType(pic.get("type").toString()); byte[] byteArray = (byte[]) pic.get("content"); ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray); try { int ind = doc.addPicture(byteInputStream,picType); doc.createPicture(ind, width , height,paragraph); System.out.println("图片替换"); } catch (Exception e) { e.printStackTrace(); } } } } if(isSetText){ run.setText(text,0); } } } } } } /** * 根据图片类型,取得对应的图片类型代码 * @param picType * @return int */ private static int getPictureType(String picType){ int res = CustomXWPFDocument.PICTURE_TYPE_PICT; if(picType != null){ if(picType.equalsIgnoreCase("png")){ res = CustomXWPFDocument.PICTURE_TYPE_PNG; }else if(picType.equalsIgnoreCase("dib")){ res = CustomXWPFDocument.PICTURE_TYPE_DIB; }else if(picType.equalsIgnoreCase("emf")){ res = CustomXWPFDocument.PICTURE_TYPE_EMF; }else if(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){ res = CustomXWPFDocument.PICTURE_TYPE_JPEG; }else if(picType.equalsIgnoreCase("wmf")){ res = CustomXWPFDocument.PICTURE_TYPE_WMF; } } return res; } /** * 将输入流中的数据写入字节数组 * @param in * @return */ public static byte[] inputStream2ByteArray(InputStream in,boolean isClose){ byte[] byteArray = null; try { int total = in.available(); byteArray = new byte[total]; in.read(byteArray); } catch (IOException e) { e.printStackTrace(); }finally{ if(isClose){ try { in.close(); } catch (Exception e2) { System.out.println("关闭流失败"); } } } return byteArray; } }
试试其它关键字
POI操作
同语言下
.
Jquery搜索框获取回车事件
.
H5页面添加倒计时,然后自动跳转
.
通过user-agent判断h5页面是在哪个手机App(QQ、微信
.
nginx 禁止未绑定的域名访问
.
JavaScript 获取按键,并屏蔽系统 Window 事件
.
H5之只允许微信浏览器打开,禁止从外部浏览器访问
.
微信打开网址添加在浏览器中打开提示的办法
.
实现JS复制、粘贴,Chrome/Firefox下可用
.
video视频播放,play()、pause()、duration时长、onen
.
HTML5实现MP3上传前的预览和播放时长的获取
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
博超
贡献的其它代码
(
13
)
.
SQL 如何去除重复的字符串
.
查询域名映射的所有IP地址
.
Snackbar相关
.
压缩相关
.
通过java反射获取任意对象的字段名及字段值
.
Java 单选复选框
.
读取XML文件通用工具类(递归调用)
.
java处理json的工具类(list,map和json的之间的转换)
.
查询今天,昨天,近7天,近30天,本月,上一月数据的方法
.
在一个ASP.Net页中实现上传照片并存入数据库,上传后
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3