工作中word模板处理,根据word中table的大小,替换文字以及自动改变文字的大小,适应表格,以及替换为图片。
代码如下
package com.jeecg.common.util.jacob;
import com.itextpdf.awt.geom.Rectangle2D;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.ImageIcon;
import org.jeecgframework.core.util.StringUtil;
import com.jacob.com.ComFailException;
import com.jacob.com.ComThread;
/*
* 利用jacob 编辑word文档
*
* */
public class WordManager {
private boolean saveOnExit;
/**
* word文档
*/
private Dispatch doc = null;
/**
* word运行程序对象
*/
private ActiveXComponent word;
/**
* 所有word文档
*/
private Dispatch documents;
List
/**
* 构造函数
*/
public WordManager() {
saveOnExit = false;
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(false));
documents = word.getProperty("Documents").toDispatch();
}
/**
* 设置参数:退出时是否保存
*
* @param saveOnExit
* true-退出时保存文件,false-退出时不保存文件
*/
public void setSaveOnExit(boolean saveOnExit) {
this.saveOnExit = saveOnExit;
}
/**
* 得到参数:退出时是否保存
*
* @return boolean true-退出时保存文件,false-退出时不保存文件
*/
public boolean getSaveOnExit() {
return saveOnExit;
}
/**
* 打开文件
*
* @param inputDoc
* 要打开的文件,全路径
* @return Dispatch 打开的文件
*/
public Dispatch open(String inputDoc) {
return Dispatch.call(documents, "Open", inputDoc).toDispatch();
}
/**
* 选定内容
*
* @return Dispatch 选定的范围或插入点
*/
public Dispatch select() {
return word.getProperty("Selection").toDispatch();
}
/**
* 把选定内容或插入点向上移动
*
* @param selection
* 要移动的内容
* @param count
* 移动的距离
*/
public void moveUp(Dispatch selection, int count) {
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveUp");
}
/**
* 把选定内容或插入点向下移动
*
* @param selection
* 要移动的内容
* @param count
* 移动的距离
*/
public void moveDown(Dispatch selection, int count) {
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveDown");
}
/**
* 把选定内容或插入点向左移动
*
* @param selection
* 要移动的内容
* @param count
* 移动的距离
*/
public void moveLeft(Dispatch selection, int count) {
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveLeft");
}
/**
* 把选定内容或插入点向右移动
*
* @param selection
* 要移动的内容
* @param count
* 移动的距离
*/
public void moveRight(Dispatch selection, int count) {
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveRight");
}
/**
* 把插入点移动到文件首位置
*
* @param selection
* 插入点
*/
public void moveStart(Dispatch selection) {
Dispatch.call(selection, "HomeKey", new Variant(6));
}
/**
* 从选定内容或插入点开始查找文本
*
* @param selection
* 选定内容
* @param toFindText
* 要查找的文本
* @return boolean true-查找到并选中该文本,false-未查找到文本
*/
public boolean find(Dispatch selection, String toFindText) {
if (toFindText == null || toFindText.equals(""))
return false;
// 从selection所在位置开始查询
Dispatch find = Dispatch.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 selection
* 选定内容
* @param newText
* 替换为文本
*/
public void replace(Dispatch selection, String newText) {
// 设置替换文本
Dispatch.put(selection, "Text", newText);
}
public void getImgWidth(Dispatch selection,String oldText){
Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
Dispatch table = Dispatch.call(tables, "Item", new Variant(1)).toDispatch();
System.out.println("Item:"+table);
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
Dispatch columns=Dispatch.get(table,"Columns").toDispatch();
System.out.println("rows:"+rows);
System.out.println("columns:"+columns);
Dispatch cell = Dispatch.call(table, "Cell", 1, 1) .toDispatch();
Dispatch Range=Dispatch.get(cell,"Range").toDispatch();
System.out.println("text:"+Dispatch.get(Range,"Text").toString());
// String data=Dispatch.get(cell,"Data").getString();
// System.out.println("data1:"+data);
//
// int n = Dispatch.get(rows, "Count").getInt();
// int c=Dispatch.get(columns, "Count").getInt();
// System.out.println("data2:"+n);
// System.out.println("data3:"+c);
}
/**
* 替换图片
*
* @param selection
* 图片的插入点
* @param imagePath
* 图片文件(全路径)
*/
public void replaceImage(Dispatch selection, String imagePath,WordTableSet set) {
try {
//
Dispatch.put(selection, "Text", "");
int tableIndex= set.getTableIndex();
int cellRowIdx=set.getCellRowIdx();
int cellColIdx=set.getCellColIdx();
int oldFontSize=set.getFontSize();
Double cellheight=set.getHeight();
double width=0;
double height=0;
ImageIcon imageIcon = new ImageIcon(imagePath);
double moveTop=0;
int oldiconWidth = imageIcon.getIconWidth();
int oldiconHeight = imageIcon.getIconHeight();
System.out.println("oldIMG:======"+imagePath+oldiconWidth + "," + oldiconHeight);
height=cellheight*0.9;
width=((oldiconWidth*cellheight)/oldiconHeight)*0.9;
//Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),"AddPicture", imagePath);
moveTop=height*0.5;
System.out.println("调整上下"+moveTop);
// for(int i=0;i
// }
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
new Variant(cellColIdx)).toDispatch();
Dispatch.call(cell, "Select");
Dispatch picture = Dispatch.call(Dispatch.get(selection,"InLineShapes").toDispatch(),"AddPicture", imagePath).toDispatch(); // 添加图片
Dispatch.call(picture, "Select"); // 选中图片
Dispatch.put(picture, "Width", new Variant(width)); // 图片的宽度
Dispatch.put(picture, "Height", new Variant(height)); // 图片的高度
Dispatch ShapeRange = Dispatch.call(picture, "ConvertToShape").toDispatch(); // 取得图片区域
Dispatch WrapFormat = Dispatch.get(ShapeRange, "WrapFormat").toDispatch(); // 取得图片的格式对象
Dispatch.put(WrapFormat, "Type", 6); // 设置环绕格式(0 - 7)下面是参数说明
//
Dispatch.call(picture, "Select");
Dispatch.put(ShapeRange, "top", new Variant(10));
WordTableSet newset =set;
newset.setSuccess(true);
wordTableSetList.remove(set);
wordTableSetList.add(newset);
// wdWrapInline 7 将形状嵌入到文字中。
// wdWrapNone 3 将形状放在文字前面。请参阅 wdWrapFront 。
// wdWrapSquare 0 使文字环绕形状。行在形状的另一侧延续。
// wdWrapThrough 2 使文字环绕形状。
// wdWrapTight 1 使文字紧密地环绕形状。
// wdWrapTopBottom 4 将文字放在形状的上方和下方。
// wdWrapBehind 5 将形状放在文字后面。
// wdWrapFront 6 将形状放在文字前面。
// Dispatch.put(ShapeRange, "Left", new Variant(100));
// Dispatch.put(ShapeRange, "top", new Variant(moveTop));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void replaceImage(Dispatch selection, String imagePath) {
try {
//Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),"AddPicture", imagePath);
Dispatch picture = Dispatch.call(Dispatch.get(selection,"InLineShapes").toDispatch(),"AddPicture", imagePath).toDispatch(); // 添加图片
Dispatch.call(picture, "Select"); // 选中图片
//Dispatch.put(picture, "Width", new Variant(100)); // 图片的宽度
//Dispatch.put(picture, "Height", new Variant(100)); // 图片的高度
Dispatch ShapeRange = Dispatch.call(picture, "ConvertToShape").toDispatch(); // 取得图片区域
Dispatch WrapFormat = Dispatch.get(ShapeRange, "WrapFormat").toDispatch(); // 取得图片的格式对象
Dispatch.put(WrapFormat, "Type", 6); // 设置环绕格式(0 - 7)下面是参数说明
// wdWrapInline 7 将形状嵌入到文字中。
// wdWrapNone 3 将形状放在文字前面。请参阅 wdWrapFront 。
// wdWrapSquare 0 使文字环绕形状。行在形状的另一侧延续。
// wdWrapThrough 2 使文字环绕形状。
// wdWrapTight 1 使文字紧密地环绕形状。
// wdWrapTopBottom 4 将文字放在形状的上方和下方。
// wdWrapBehind 5 将形状放在文字后面。
// wdWrapFront 6 将形状放在文字前面。
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 替换表格
*
* @param selection
* 插入点
* @param tableName
* 表格名称,形如table$1@1、[email protected]$R@N,R代表从表格中的第N行开始填充,
* N代表word文件中的第N张表
* @param fields
* 表格中要替换的字段与数据的对应表
*/
public void replaceTable(Dispatch selection, String tableName, List dataList) {
if (dataList.size() == 1) {
System.out.println("Empty table!");
return;
}
// 要填充的列
String[] cols = (String[]) dataList.get(0);
// 表格序号
String tbIndex = tableName.substring(tableName.lastIndexOf("@") + 1);
// 从第几行开始填充
int fromRow = Integer.parseInt(tableName.substring(
tableName.lastIndexOf("$") + 1, tableName.lastIndexOf("@")));
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tbIndex))
.toDispatch();
// 表格的所有行
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
// 填充表格
for (int i = 1; i < dataList.size(); i++) {
// 某一行数据
String[] datas = (String[]) dataList.get(i);
// 在表格中添加一行
if (Dispatch.get(rows, "Count").getInt() < fromRow + i - 1)
Dispatch.call(rows, "Add");
// 填充该行的相关列
for (int j = 0; j < datas.length; j++) {
// 得到单元格
Dispatch cell = Dispatch.call(table, "Cell",
Integer.toString(fromRow + i - 1), cols[j])
.toDispatch();
// 选中单元格
Dispatch.call(cell, "Select");
// 设置格式
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font, "Bold", "0");
Dispatch.put(font, "Italic", "0");
// 输入数据
Dispatch.put(selection, "Text", datas[j]);
}
}
}
/**
* 保存文件
*
* @param outputPath
* 输出文件(包含路径)
*/
public void save(String outputPath) {
Dispatch.call(
(Dispatch) Dispatch.call(word, "WordBasic").getDispatch(),
"FileSaveAs", outputPath);
}
/**
* 关闭文件
*
* @param document
* 要关闭的文件
*/
public void close(Dispatch doc) {
Dispatch.call(doc, "Close", new Variant(saveOnExit));
}
/**
* 退出程序
*
*/
public void quit() {
word.invoke("Quit", new Variant[0]);
ComThread.Release();
}
/**
* 根据模板、数据生成word文件
*
* @param inputPath
* 模板文件(包含路径)
* @param outPath
* 输出文件(包含路径)
* @param data
* 数据包(包含要填充的字段、对应的数据)
*/
public void toTableWord(String inputPath, String outPath, HashMap data) {
String oldText;
Object param;
String newValue="";
// ComThread.InitSTA();
ComThread.InitMTA(true);
try {
System.out.println("word替换开始时间"+ new Date());
doc = open(inputPath);
//获取table表格的数据
wordTableSetList=getTableCellWidthHeight();
// System.out.println("word已开始");
Dispatch selection = select();
moveStart(selection);
Iterator keys = data.keySet().iterator();
// System.out.println("word获取数据");
while (keys.hasNext()) {
oldText = (String) keys.next();
param = data.get(oldText);
if(param==null){
param=" ";
}
if (param instanceof Integer) {
int value = ((Integer) param).intValue();
newValue = String.valueOf(value);;
} else if (param instanceof String) {
newValue= (String) param;
} else if (param instanceof Double) {
double d = ((Double) param).doubleValue();
newValue = String.valueOf(d);;
} else if (param instanceof Float) {
float f = ((Float) param).floatValue();
newValue = String.valueOf(f);;
} else if (param instanceof Long) {
long l = ((Long) param).longValue();
newValue = String.valueOf(l);
} else if (param instanceof Boolean) {
boolean b = ((Boolean) param).booleanValue();
newValue = String.valueOf(b);;
} else if (param instanceof Date) {
Date d = (Date) param;
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
newValue = df1.format(d);
}else if (param instanceof BigDecimal) {
BigInteger l = ((BigDecimal) param).toBigInteger();
newValue = String.valueOf(l);
}
// System.out.println("word:"+oldText+newValue);
replaceTableAll(selection, oldText, newValue);
}
save(outPath);
} catch (Exception e) {
System.out.println("错误"+e.getMessage());
// debug.println("toword[Java2Word]------------操作word文件失败!"+e.getMessage(),true);
} finally {
if (doc != null) {
close(doc);
}
quit();
System.out.println("word替换结束时间"+ new Date());
}
}
public void toWord(String inputPath, String outPath, HashMap data) {
String oldText;
Object param;
String newValue="";
// ComThread.InitSTA();//单一线程启动
ComThread.InitMTA(true);
try {
// System.out.println("word替换开始");
doc = open(inputPath);
//获取table表格的数据
// wordTableSetList=getTableCellWidthHeight();
// System.out.println("word已开始");
Dispatch selection = select();
moveStart(selection);
Iterator keys = data.keySet().iterator();
// System.out.println("word获取数据");
while (keys.hasNext()) {
oldText = (String) keys.next();
param = data.get(oldText);
if(param==null){
param=" ";
}
if (param instanceof Integer) {
int value = ((Integer) param).intValue();
newValue = String.valueOf(value);;
} else if (param instanceof String) {
newValue= (String) param;
} else if (param instanceof Double) {
double d = ((Double) param).doubleValue();
newValue = String.valueOf(d);;
} else if (param instanceof Float) {
float f = ((Float) param).floatValue();
newValue = String.valueOf(f);;
} else if (param instanceof Long) {
long l = ((Long) param).longValue();
newValue = String.valueOf(l);
} else if (param instanceof Boolean) {
boolean b = ((Boolean) param).booleanValue();
newValue = String.valueOf(b);;
} else if (param instanceof Date) {
Date d = (Date) param;
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
newValue = df1.format(d);
}else if (param instanceof BigDecimal) {
BigInteger l = ((BigDecimal) param).toBigInteger();
newValue = String.valueOf(l);
}
// System.out.println("word:"+oldText+newValue);
replaceAll(selection, oldText, newValue);
}
save(outPath);
} catch (Exception e) {
System.out.println("错误"+e.getMessage());
// debug.println("toword[Java2Word]------------操作word文件失败!"+e.getMessage(),true);
} finally {
if (doc != null) {
close(doc);
}
quit();
}
}
/**
* 将输入流中的数据写入字节数组
* @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;
}
public List
List
for(int k = 0;k < wordTableSetList.size();k++){
WordTableSet set = wordTableSetList.get(k);
set.setRownum(k);
if(text.equals(set.getOldText())&&!set.isSuccess){
widHeight.add(set);
}
}
return widHeight;
}
//获取所有表格中内容cell的宽度高度
public List
List
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 获取表格数目
int tablesCount = Dispatch.get(tables,"Count").toInt();
// System.out.println("获取表格数目"+tablesCount);
// 循环获取表格
for(int i=1;i<=tablesCount;i++)
{
// 生产warningBean
/// warningBean warning = new warningBean();
// 获取第i个表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(i)).toDispatch();
// 获取该表格所有行
Dispatch rows = Dispatch.call(table, "Rows").toDispatch();
// 获取该表格所有列
Dispatch columns = Dispatch.call(table, "Columns").toDispatch();
// 获取该表格行数
int rowsCount = Dispatch.get(rows,"Count").toInt();
// 获取该表格列数
int columnsCount = Dispatch.get(columns,"Count").toInt();
// Dispatch Range2=Dispatch.get(table,"Range").toDispatch();
// System.out.println( Dispatch.get(Range2,"Text").toString());
// 循环遍历行
for(int j=1;j<=rowsCount;j++)
for(int m=1;m<=columnsCount;m++)
{
try {
WordTableSet WordTableSet = getTxtFromCell(i, j, m);
if(WordTableSet!=null){
mapList.add(WordTableSet);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return mapList;
}
public WordTableSet getTxtFromCell(int tableIndex, int cellRowIdx, int cellColIdx) throws UnsupportedEncodingException {
WordTableSet set=new WordTableSet();
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();
Dispatch rows = Dispatch.call(table, "Rows").toDispatch();
Dispatch columns = Dispatch.call(table, "Columns").toDispatch();
// System.out.println("表格:"+tableIndex+"行数"+cellRowIdx+"列数"+cellColIdx+"其他行列"+rows+columns);
Map
String widHei="";
String ret = "";
try{
Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),new Variant(cellColIdx)).toDispatch();
Dispatch Range=Dispatch.get(cell,"Range").toDispatch();
Double widths=Dispatch.get(cell,"Width").toDouble();
Double Height=Dispatch.get(cell,"Height").toDouble();
String eeheight= Dispatch.get(cell,"HeightRule").toString();
Dispatch font = Dispatch.get(Range, "Font").toDispatch();
int fontSize=Dispatch.get(font,"Size").toInt();
widHei=widths+","+Height;
String t=Dispatch.get(Range,"Text").toString();
String s=new String(t.getBytes("utf-8"));
s=s.replace("","").trim();
// System.out.print(s+" ");
ret=s;
// Dispatch.call(cell, "Select");
// ret = Dispatch.get(selection, "Text").toString();
// ret = ret.substring(0, ret.length() - 2); // 去掉最后的回车符;
//cell里面含有图片
if(fontSize==9999999){
return null;
}
Dispatch.call(cell, "Select");
// Dispatch selection= select();
// System.out.println("表格:"+tableIndex+"内容="+ret+"行数"+cellRowIdx+"列数"+cellColIdx+"宽度"+widths+""+Height+eeheight);
maps.put(ret, widHei);
set.setFontSize(fontSize);
set.setCellColIdx(cellColIdx);
set.setCellRowIdx(cellRowIdx);
set.setHeight(Height);
set.setWidth(widths);
set.setTableIndex(tableIndex);
set.setOldText(ret);
set.setSelection(cell);
//没有行列
}catch (ComFailException e){
return set;
}
return set;
}
/**
* 在指定的单元格里填写数据
*
* @param tableIndex
* @param cellRowIdx
* @param cellColIdx
* @param txt
* @throws UnsupportedEncodingException
*/
public void putTxtToCell(Dispatch selection,
String txt,WordTableSet set ) {
int tableIndex= set.getTableIndex();
int cellRowIdx=set.getCellRowIdx();
int cellColIdx=set.getCellColIdx();
int oldFontSize=set.getFontSize();
Double oldHeight=set.getHeight();
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
new Variant(cellColIdx)).toDispatch();
Dispatch.call(cell, "Select");
//字体公共参数
double tt=0.52;
int textLength=length(txt);
int cellHeight=Dispatch.get(cell,"Height").toInt();
int cellWidth=Dispatch.get(cell,"Width").toInt();
int fontSize=0;
int lineHeight=0;
boolean flag=true;
while(flag){
for(int i=oldFontSize;i>0;i--){
lineHeight=i+1;
int hang=cellHeight/lineHeight;
int zhang=hang*cellWidth;
double texthang= textLength*i*tt;
if(zhang>=texthang){
flag=false;
fontSize=i;
break;
}
}
}
Dispatch.put(cell, "HeightRule", new Variant(1));//0-自动wdRowHeightAuto,1-最小值wdRowHeightAtLeast, 2-固定wdRowHeightExactly
Dispatch alignment = Dispatch.get(selection, "ParagraphFormat")
.toDispatch();
Dispatch.put(alignment, "LineSpacingRule" , new Variant(4));
Dispatch.put(alignment, "LineSpacing" , new Variant(lineHeight));
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font, "Size", new Variant(fontSize));
// String WordSpacing1=Dispatch.get(font, "Spacing").toString();
Dispatch.put(selection, "Text", txt);
// System.out.println("字符长度==="+length(txt)+"原始字体大小="+oldFontSize+"使用字体大小="+fontSize+"内容="+txt);
WordTableSet newset =set;
newset.setSuccess(true);
wordTableSetList.remove(set);
wordTableSetList.add(newset);
// // 所有表格
// Dispatch tables1 = Dispatch.get(doc, "Tables").toDispatch();
// // 要填充的表格
// Dispatch table1 = Dispatch.call(tables1, "Item", new Variant(tableIndex))
// .toDispatch();
//
// Dispatch cell1 = Dispatch.call(table1, "Cell", new Variant(cellRowIdx),
// new Variant(cellColIdx)).toDispatch();
//
// Dispatch.call(cell1, "Select");
// // Dispatch paragraphs = Dispatch.get(selection, "Paragraphs").toDispatch();
// Dispatch alignment1 = Dispatch.get(selection, "ParagraphFormat")
// .toDispatch();
// String Alignment1= Dispatch.get(alignment1, "Alignment").toString();// 默认:居左 0:居左 1:居中 2:居右 3:两端对齐 4:分散对齐
// String LineSpacingRule1=Dispatch.get(alignment1, "LineSpacingRule").toString();//默认:1.0 0:1.0 1:1.5 2:2.0 3:最小值 4:固定值
// String LineSpacing1=Dispatch.get(alignment1, "LineSpacing").toString();
//
// System.out.println("段落以及行距========"+Alignment1+" 行距类型"+LineSpacingRule1+" 行距 "+LineSpacing1+"字距"+WordSpacing1);
//
// Dispatch Range=Dispatch.get(cell1,"Range").toDispatch();
// String t=Dispatch.get(Range,"Text").toString();
// try {
// String s=new String(t.getBytes("utf-8"));
// System.out.println("7dadsdadassdasaddasafasaffaasfasf========"+s+cellRowIdx+cellColIdx);
// System.out.println("7dadsdadassdasaddasafasaffaasfasf========"+oldHeight);
// } catch (UnsupportedEncodingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
//计算字符长度
public static int length(String value) {
int valueLength = 0;
String chinese = "[\u0391-\uFFE5]";
/* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */
for (int i = 0; i < value.length(); i++) {
/* 获取一个字符 */
String temp = value.substring(i, i + 1);
/* 判断是否为中文字符 */
if (temp.matches(chinese)) {
/* 中文字符长度为2 */
valueLength += 2;
} else {
/* 其他字符长度为1 */
valueLength += 1;
}
}
return valueLength;
}
/**
* 全局替换
*
* @param selection
* 选定内容或起始插入点
* @param oldText
* 要替换的文本
* @param newText
* 替换为文本
*/
public void replaceAll(Dispatch selection, String oldText, Object replaceObj) {
// 移动到文件开头
moveStart(selection);
if (oldText.startsWith("table") || replaceObj instanceof List) {
replaceTable(selection, oldText, (List) replaceObj);
} else {
String newText = (String) replaceObj;
if (oldText.indexOf("image") != -1
|| newText.lastIndexOf(".bmp") != -1
|| newText.lastIndexOf(".png") != -1
|| newText.lastIndexOf(".jpg") != -1
|| newText.lastIndexOf(".gif") != -1){
while (find(selection, oldText)) {
//getImgWidth(selection,oldText);
replaceImage(selection, newText);
Dispatch.call(selection, "MoveRight");
}
}else{
while (find(selection, oldText)) {
replace(selection, newText);
Dispatch.call(selection, "MoveRight");
}
}
}
}
public void replaceTableAll(Dispatch selection, String oldText, Object replaceObj) {
// 移动到文件开头
moveStart(selection);
if (oldText.startsWith("table") || replaceObj instanceof List) {
replaceTable(selection, oldText, (List) replaceObj);
} else {
String newText = (String) replaceObj;
if (oldText.indexOf("image") != -1
|| newText.lastIndexOf(".bmp") != -1
|| newText.lastIndexOf(".png") != -1
|| newText.lastIndexOf(".jpg") != -1
|| newText.lastIndexOf(".gif") != -1){
while (find(selection, oldText)) {
//getImgWidth(selection,oldText);
List
if(setList!=null&&setList.size()>0){
for(WordTableSet set:setList){
replaceImage(selection, newText,set);
}
}else{
replaceImage(selection, newText);
}
Dispatch.call(selection, "MoveRight");
}
}else{
while (find(selection, oldText)) {
List
if(setList!=null&&setList.size()>0){
for(WordTableSet set:setList){
putTxtToCell(selection,newText,set);
}
}else{
replace(selection, newText);
}
Dispatch.call(selection, "MoveRight");
}
}
}
}
public static void main(String[] args) throws Exception {
WordManager j = new WordManager();
String inputPath = "E:/111.doc";
String outPath = "E:/111d.doc";
HashMap
//不能为空
// Map
// header.put("width", 100);
// header.put("height", 150);
// header.put("type", "png");
// header.put("content", inputStream2ByteArray(new FileInputStream("D:\\aa.jpg"), true));
// data.put("[$图片]", "D:\\a.png");F字符长度
String aaa="见证取样";
data.put("${CODE}", "181501341077");
data.put("${[0].PRO_NAME}", "sdsadsdasadasdasdsadsdd大大dddddddddddddddddddddddddddddddddddddddddddddddddddddadasdadssdsaasdadsunchengmandadadasdsddddddddddddddddddddddddddddddddddddddddadssadasasdasads");
data.put("${[0].TEST_NO}", "增长速度噶大苏打");
data.put("${[0].IMG1}", "E:\\1.png");
j.toTableWord(inputPath, outPath, data);
//System.out.print(length(aaa));
//打开本地文件
//Desktop.getDesktop().open(new File("D:\\tt.doc"));
}
}