工作中用于word替换文字模板,根据word中的表格的大小自动替换文字,以及改变文字的大小适应表格,和改变图片的大小适应表格,长话短说,代码如下,其中有一个bug,就是中英文会出现换行的问题,暂时没有解决,另一篇文章用jacob替换不会出现这个问题,但是多线程运用中会出现CPU饱满的情况
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//E:\\111.doc
//
String FilePath="E:\\20190813135916h4ZQLC3g.doc";
String outPath="E:\\111c.doc";
HashMap data =new HashMap
data.put("${CODE}", "181501341077:,.");
data.put("${[0].PRO_NAME}", "sdsadsdasadasdasdsadsdd大大撒dddddddddddddddddddddddddddddddddddddddddddddddddddddadasdadssdsaasdadsunchengmandadadasdsddddddddddddddddddddddddddddddddddddddddadssadasasdasads");
data.put("${[0].TEST_NO}", "增长速度噶大苏打");
data.put("${[0].IMG1}", "E:\\1.png");
data.put("${[0].JIANZHENGDW}", "sdsadsdasadasdasdsadsdd大大撒打算sdsadsdasadasdasdsadsdd");
data.put("${[0].JIANZHENGR}", "sdsadsdasadasdasdsadsdd额啊大大士大夫sdsadsdasadasdasdsadsdd");
data.put("${[0].JIANYANLEIBIE}", "sdsadsdasadasdasdsadsdd大大撒发达");
data.put("${[0].QUYANGR}", "大大撒发达");
data.put("${[0].SONGYANGR}", "日期提前打达成");
toTableWord(FilePath,outPath,data);
//extractImagesToFiles();
//Conversion("E://AAA//Image1Out.wmf","E://AAA//1111.png");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void toTableWord(String FilePath,String outPath,HashMap
Document doc;
String s = "
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
License license = new License();
license.setLicense(is);
doc = new Document(FilePath);
//替换表格
//获取第一个表格
Table table = (Table)doc.getChild(NodeType.TABLE, 0, true);
DocumentBuilder builder = new DocumentBuilder(doc);
RowCollection rows = table.getRows();
System.out.println("rows==="+rows.getCount());
for (int i = 1; i < rows.getCount(); i++) {
Row row = rows.get(i);
double cellheight= row.getRowFormat().getHeight();
double CellSpacing=row.getRowFormat().getCellSpacing();
//Cell cell = row.getCells().get(0);
//System.out.println(cellheight+"===rows==="+row.getCells().getCount());
for(int j=1; j
if(null != cell ){
String text = cell.getText().trim();
if(null != text && !"".equals(text)){
double Cellwidth= cell.getCellFormat().getWidth();
//System.out.println(Cellwidth+"===text==="+text);
String newText= replaceText(text,data);
if(newText!=""){
//图片
if(newText.lastIndexOf(".bmp") != -1|| newText.lastIndexOf(".png") != -1|| newText.lastIndexOf(".jpg") != -1
|| newText.lastIndexOf(".gif") != -1){
cell.getParagraphs().clear();
//插入图片
builder.moveToCell(0, i, j, 0);
ImageIcon imageIcon = new ImageIcon(newText);
int oldiconWidth = imageIcon.getIconWidth();
int oldiconHeight = imageIcon.getIconHeight();
double height=cellheight*0.9;
double width=((oldiconWidth*cellheight)/oldiconHeight)*0.9;
builder.insertImage(newText, RelativeHorizontalPosition.MARGIN, 0,RelativeVerticalPosition.MARGIN, 0,width,height, WrapType.NONE);//147表示图片的高度,WrapType.INLINE表示图片的嵌入方式
}else{
//System.out.println(cell.getParagraphs().getCount()+"cellCount===="+cell.getFirstParagraph().getRuns().getCount());
//Font font= cell.getFirstParagraph().getRuns().get(0).getFont();
Style style= cell.getFirstParagraph().getParagraphFormat().getStyle();
ParagraphFormat oldParagraphFormat=cell.getFirstParagraph().getParagraphFormat();
int paragraphsCount= cell.getParagraphs().getCount();
//System.out.println("paragraphsCount"+paragraphsCount);
if(paragraphsCount==1){
cell.getParagraphs().clear();
builder.moveToCell(0, i, j, 0);
Font font= builder.getFont();
int oldFontSize=(int) font.getSize();
int spacing=(int) font.getSpacing();
//字体公共参数
double tt=0.52;
int textLength=length(newText);
int fontSize=0;
int lineHeight=0;
boolean flag=true;
// System.out.println("字体spacing=="+spacing);
// System.out.println("字体Cellspacing=="+CellSpacing);
// System.out.println("字体字符长=="+textLength);
// System.out.println(Cellwidth+"==单元格长度高度=="+cellheight);
while(flag){
for(int m=oldFontSize;m>0;m--){
lineHeight=m+1;
int hang=(int) (cellheight/lineHeight);
int zhang=(int) (hang*Cellwidth);
double texthang= textLength*m*tt;
if(zhang>=texthang){
flag=false;
fontSize=m;
break;
}
}
}
//System.out.println(oldFontSize+"字体"+fontSize);
//fontSize=3;
builder.getParagraphFormat().setAlignment(oldParagraphFormat.getAlignment());
builder.getParagraphFormat().setStyleIdentifier(oldParagraphFormat.getStyleIdentifier());
builder.getParagraphFormat().setStyle(style);
builder.getFont().setSize(fontSize);
//builder.getFont().setSpacing(lineHeight);
//System.out.println(builder.getParagraphFormat().getLineSpacingRule()+"行距"+builder.getParagraphFormat().getLineSpacing()+"==="+lineHeight);
builder.getParagraphFormat().setLineSpacingRule(4);
builder.getFont().setSpacing(0);
builder.getParagraphFormat().setLineSpacing(0);
// System.out.println("getBidi===="+builder.getParagraphFormat().getBidi());
// System.out.println("getKeepTogether===="+builder.getParagraphFormat().getKeepTogether());
// System.out.println("getKeepWithNext===="+builder.getParagraphFormat().getKeepWithNext());
// System.out.println("getNoSpaceBetweenParagraphsOfSameStyle===="+ builder.getParagraphFormat().getNoSpaceBetweenParagraphsOfSameStyle());
// System.out.println("getPageBreakBefore===="+builder.getParagraphFormat().getPageBreakBefore());
// System.out.println("getSpaceAfterAuto===="+builder.getParagraphFormat().getSpaceAfterAuto());
// System.out.println("getSpaceBeforeAuto===="+builder.getParagraphFormat().getSpaceBeforeAuto());
// System.out.println("=getSuppressAutoHyphens==="+ builder.getParagraphFormat().getSuppressAutoHyphens());
// System.out.println("getSuppressLineNumbers===="+ builder.getParagraphFormat().getSuppressLineNumbers());
// System.out.println("getWidowControl===="+ builder.getParagraphFormat().getWidowControl());
// System.out.println(builder.getRowFormat().getAllowAutoFit());
// System.out.println(builder.getRowFormat().getAllowBreakAcrossPages());
//
// System.out.println(builder.getCellFormat().getWrapText());
// System.out.println(builder.getCellFormat().getFitText());
builder.getParagraphFormat().setBidi(oldParagraphFormat.getBidi());
builder.getParagraphFormat().setKeepTogether(oldParagraphFormat.getKeepTogether());
builder.getParagraphFormat().setKeepWithNext(oldParagraphFormat.getKeepWithNext());
builder.getParagraphFormat().setNoSpaceBetweenParagraphsOfSameStyle(oldParagraphFormat.getNoSpaceBetweenParagraphsOfSameStyle());
builder.getParagraphFormat().setPageBreakBefore(oldParagraphFormat.getPageBreakBefore());
builder.getParagraphFormat().setSpaceAfterAuto(oldParagraphFormat.getSpaceAfterAuto());
builder.getParagraphFormat().setSpaceBeforeAuto(oldParagraphFormat.getSpaceBeforeAuto());
builder.getParagraphFormat().setSuppressAutoHyphens(oldParagraphFormat.getSuppressAutoHyphens());
builder.getParagraphFormat().setSuppressLineNumbers(oldParagraphFormat.getSuppressLineNumbers());
builder.getParagraphFormat().setWidowControl(oldParagraphFormat.getWidowControl());
// builder.getRowFormat().setAllowAutoFit(true);
//System.out.println(builder.getParagraphFormat().getLineSpacingRule()+"行距2"+builder.getParagraphFormat().getLineSpacing());
builder.write(newText.trim());
}else{
//System.out.println(text+"====新内容=="+newText);
//cell.getRange().replace(text, newText, true, false);
}
//cell.getFirstParagraph().getRuns().get(0).setText(newText);
}
}
//设置新内容
//cell.getFirstParagraph().getRuns().get(0).setText("1");
//cell.getFirstParagraph().getRuns().clear();;
}
}
}
}
//替换段落
Iterator keys = data.keySet().iterator();
while (keys.hasNext()) {
String oldText = (String) keys.next();
String newValue="";
Object 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);
}
doc.getRange().replace(oldText, newValue, true, false);
}
doc.save(outPath);
}
public static String replaceText(String text,HashMap
Iterator keys = data.keySet().iterator();
String newText="";
String oldText="";
Object param="";
String newValue="";
// text=text.replace("", "");
// text=text.replace(":", "");
// 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);
}
if(text.contains(oldText)){
//图片
if( newValue.lastIndexOf(".bmp") != -1|| newValue.lastIndexOf(".png") != -1|| newValue.lastIndexOf(".jpg") != -1
|| newValue.lastIndexOf(".gif") != -1)
{
text=newValue;
//文字
}else{
text=text.replace(oldText, newValue);
}
}else{
}
}
return text;
}
public static void fitTableToPageWidth(Table table) {
//Get the page settings from the section where the table occurs, as each section can have different page settings.
Section section = (Section) table.getAncestor(NodeType.SECTION);
//First run simply gets the table size (the widest row). This is used to calculate the ratio below instead of just each row length
//as the last cell in one row could be shorter than the last cell in the other row. This will preserve these different sizes when fitting.
double tableWidth = 0;
for (Row row : table.getRows()) {
double rowWidth = 0;
for (Cell cell : row.getCells()) {
rowWidth += cell.getCellFormat().getWidth();
cell.getCellFormat().setFitText(true);
}
//If this row is larger than previous set this width as the longest row.
if (rowWidth > tableWidth)
{
tableWidth = rowWidth;
}
}
//Calculate the width of the page
double pageWidth = section.getPageSetup().getPageWidth() - (section.getPageSetup().getLeftMargin() + section.getPageSetup().getRightMargin());
//In the second run set each cell in the row proportionally to the width of the page
for(Row row : table.getRows()) {
for(Cell cell : row.getCells())
{
//Calculate the ratio of each cell to the row width and then translate this ratio to the page width.
double cellRatio = cell.getCellFormat().getWidth() / tableWidth;
cell.getCellFormat().setWidth(cellRatio * pageWidth);
}
}
}
//计算字符长度
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;
}