您好,欢迎访问三七文档
当前位置:首页 > 行业资料 > 国内外标准规范 > Java通过POI和JXL给Excel动态添加水印
一:设置水印要显示的model类(非必要)packagezp.ExcelUtil;importjava.text.SimpleDateFormat;importjava.util.Date;publicclassModel{privateStringip;privateStringuser;privateDatedate;publicModel(){//TODOAuto-generatedconstructorstub}publicModel(Stringip,Stringuser,Datedate){this.ip=ip;this.user=user;this.date=date;}publicStringgetIp(){returnip;}publicvoidsetIp(Stringip){this.ip=ip;}publicStringgetUser(){returnuser;}publicvoidsetUser(Stringuser){this.user=user;}publicStringgetDate(){SimpleDateFormatsdf=newSimpleDateFormat(yyyy年MM月dd日HH时mm分ss秒);returnsdf.format(date);}publicvoidsetDate(Datedate){this.date=date;}}二.编写工具类packagezp.ExcelUtil;importjava.awt.AlphaComposite;importjava.awt.BasicStroke;importjava.awt.Color;importjava.awt.Font;importjava.awt.Graphics2D;importjava.awt.font.FontRenderContext;importjava.awt.geom.Rectangle2D;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.IOException;importjava.lang.reflect.Method;importjava.util.HashMap;importjava.util.Iterator;importjava.util.Map;importjavax.imageio.ImageIO;importorg.json.JSONException;importorg.json.JSONObject;publicclassUtilss{privatestaticintwidth=900;//水印图片的宽度privatestaticintheight=1020;//水印图片的高度因为设置其他的高度会有黑线,所以拉高高度/***将JavaBean转换成JSONObject(通过Map中转)**@parambean*javaBean*@returnjson对象*@throwsException*/publicstaticJSONObjectmodelToJSON(Objectbean)throwsException{returnnewJSONObject(toMap(bean));}/***将Javabean转换为Map**@paramjavaBean*javaBean*@returnMap对象*/@SuppressWarnings({unchecked,rawtypes})publicstaticMaptoMap(ObjectjavaBean)throwsException{Mapresult=newHashMap();Method[]methods=javaBean.getClass().getDeclaredMethods();for(Methodmethod:methods){if(method.getName().startsWith(get)){Stringfield=method.getName();field=field.substring(field.indexOf(get)+3);field=field.toLowerCase().charAt(0)+field.substring(1);Objectvalue=method.invoke(javaBean,(Object[])null);result.put(field,null==value?:value.toString());}}returnresult;}/***将Json对象转换成Map**@paramjsonObject*json对象*@returnMap对象*@throwsJSONException*/@SuppressWarnings({rawtypes,unchecked})publicstaticMaptoMap(StringjsonString)throwsJSONException{JSONObjectjsonObject=newJSONObject(jsonString);Mapresult=newHashMap();Iteratoriterator=jsonObject.keys();Stringkey=null;Stringvalue=null;while(iterator.hasNext()){key=(String)iterator.next();value=jsonObject.getString(key);result.put(key,value);}returnresult;}/***生成水印图片**@paramwatermark*@return*@throwsIOException*/publicstaticFilecreateWaterMark(Stringwatermark)throwsIOException{intwidth=800;intheight=1020;Filefile=newFile(watermark.bmp);Fontfont=newFont(Serif,Font.ITALIC,20);BufferedImagebi=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);Graphics2Dg2=bi.createGraphics();//设置字体颜色为灰色g2.setColor(Color.LIGHT_GRAY);//设置字体g2.setFont(font);//设置字体倾斜度g2.rotate(Math.toRadians(0),(double)bi.getWidth()/2,(double)bi.getHeight()/2);g2.setBackground(Color.WHITE);g2.clearRect(0,0,width,height);FontRenderContextcontext=g2.getFontRenderContext();Rectangle2Dbounds=font.getStringBounds(watermark,context);doublex=(width-bounds.getWidth())/2;doubley=(height-bounds.getHeight())/2;doubleascent=-bounds.getY();doublebaseY=y+ascent;g2.drawString(watermark,(int)x,(int)baseY);//ImageIO.write(bi,bmp,file);//通过bmp写入文件//BMPEncoder.write(bi,file);returnfile;}@SuppressWarnings({rawtypes,unchecked})publicstaticMapcreateWaterMark1(MapwatermarkMessage)throwsIOException{Mapmap=newHashMap();Filefile=newFile(watermark.bmp);//获取bufferedImage对象BufferedImagebi=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//处理背景色,设置为白色intminx=bi.getMinX();intminy=bi.getMinY();for(inti=minx;iwidth;i++){for(intj=miny;jheight;j++){bi.setRGB(i,j,0xffffff);}}//获取Graphics2d对象Graphics2Dg2d=bi.createGraphics();//设置字体颜色为灰色g2d.setColor(Color.LIGHT_GRAY);//设置图片的属性g2d.setStroke(newBasicStroke(1));//设置字体g2d.setFont(newFont(Serif,Font.ITALIC,40));//设置字体倾斜度g2d.rotate(Math.toRadians(-8));//写入水印文字原定高度过小,所以累计写水印,增加高度for(inti=1;i7;i++){Object[]key=watermarkMessage.keySet().toArray();for(intj=0;jkey.length;j++){if(key[j].equals(date)){g2d.drawString(日期:+watermarkMessage.get(key[j]),0,180*i+40*(j+1));}elseif(key[j].equals(user)){g2d.drawString(用户:+watermarkMessage.get(key[j]),0,180*i+40*(j+1));}elseif(key[j].equals(ip)){g2d.drawString(IP地址:+watermarkMessage.get(key[j]),0,180*i+40*(j+1));}else{g2d.drawString((String)key[j]+:+watermarkMessage.get(key[j]),0,180*i+40*(j+1));}}}//设置透明度g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));//释放对象g2d.dispose();//通过bmp写入文件//BMPEncoder.write(bi,file);ImageIO.write(bi,bmp,file);map.put(file,file);map.put(width,width);map.put(height,height);returnmap;}}三.编写处理类packagezp.ExcelUtil;importjava.io.File;importjava.io.FileInputStream;importjava.io.InputStream;importjava.util.Map;importorg.json.JSONObject;importjxl.Workbook;importjxl.write.WritableSheet;importjxl.write.WritableWorkbook;publicclassExcelUtil{/****@paramxls_filePath_in要添加水印的excel文件路径(必须是*.xls文件,如/in.xls)*@paramxls_filePath_outexcel文件输出路径(必须是*.xls文件,如/out.xls)*@paramwatermarkText*@throwsException*/@Suppres
本文标题:Java通过POI和JXL给Excel动态添加水印
链接地址:https://www.777doc.com/doc-2881618 .html