jxls模板导出图片

    用jxls模板比较开心的就是,不须要在excle数格子,只要建立excle模板后,就可以快速获得本身想要的excel了。不过也有限制,就是若是须要导出图片的话,仍是须要本身手动编写代码来解决这个问题。我想到的解决方法既然是在原来jar包中没有对应的解决方法,那么为何不在动手添加这个功能呢?在2.*版本中,这个功能是有的。不过仍是比较喜欢这种相似于jstl的书写语言。 看了一下源代码,感受改写起来仍是比较简单的,决定这么改写1.*版本的jar包。html

package net.sf.jxls.tag;

import net.sf.jxls.parser.Expression;
import net.sf.jxls.transformation.ResultTransformation;
import net.sf.jxls.transformer.Configuration;
import net.sf.jxls.transformer.Sheet;
import net.sf.jxls.transformer.SheetTransformer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.jexl2.UnifiedJEXL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by mjm on 16/11/14.
 */
public class ImageTag extends BaseTag {

    protected static final Log log = LogFactory.getLog(OutTag.class);

    public static final String TAG_NAME = "image";

    private Configuration configuration = new Configuration();
    private TagContext tagContext;
    private String src;
    private String type;
    private Integer x;
    private Integer y;

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }


    public String getSrc() {
        return src;
    }

    public void setSrc(String source) {
        this.src = source;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Integer getX() {
        return x;
    }

    public void setX(Integer x) {
        this.x = x;
    }

    public Integer getY() {
        return y;
    }

    public void setY(Integer y) {
        this.y = y;
    }

    public TagContext getTagContext() {
        return tagContext;
    }

    public void init(TagContext context) {
        this.tagContext = context;
    }

    /**
     * @param sheetTransformer
     * @return number of rows to shift
     */
    public ResultTransformation process(SheetTransformer sheetTransformer) {

        ResultTransformation resultTransformation = new ResultTransformation(0);

        if(null != null){
            try {
                Block block = getTagContext().getTagBody();
                int rowNum = block.getStartRowNum();
                int cellNum = block.getStartCellNum();

                Sheet jxlsSheet = getTagContext().getSheet();
                if (jxlsSheet != null) {
                    org.apache.poi.ss.usermodel.Sheet sheet = jxlsSheet.getPoiSheet();
                    if (sheet != null) {
                        Row row = sheet.getRow(rowNum);
                        if (row != null) {
                            Cell cell = row.getCell((short) cellNum);
                            if (cell != null) {
                                Object value = new Expression(src, tagContext.getBeans(), configuration).evaluate();

                                String fixedValue = value.toString();

                                if (value == null) {
                                    cell.setCellValue(sheet.getWorkbook().getCreationHelper().createRichTextString(""));
                                }else{

                                    HSSFPatriarch patriarch = (HSSFPatriarch) sheet.createDrawingPatriarch();
                                    if(null==x){
                                        x=0;
                                    }
                                    if(null==y){
                                        y=0;
                                    }
                                    //                                    XSSFDrawing patriarch = sheet.createDrawingPatriarch();//建立绘图工具对象
                                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023,100,(short) (cell.getColumnIndex()-1), cell.getRowIndex()-1, (short)(cell.getColumnIndex()+x), cell.getRowIndex()+y);

                                    String classPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();

                                    File imageFile = new File(classPath + File.separator + "resources" + File.separator+ getFileName(fixedValue));


                                    URL httpUrl = new URL(fixedValue);
                                    FileUtils.copyURLToFile(httpUrl, imageFile);
                                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                    BufferedImage BufferImg = ImageIO.read(imageFile);
                                    ImageIO.write(BufferImg, "JPEG", bos);

                                    patriarch.createPicture(anchor,sheet.getWorkbook().addPicture(bos.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));

                                }
                            }
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("Cell expression evaluation has failed.", e);
            }

        }
        return resultTransformation;
    }

    /**
     * 用正则表达式获取文件的文件名后缀名  如:test.java
     * @author kxn
     */
    public static String getFileName(String url) {
        String suffixes = "avi|mpeg|3gp|mp3|mp4|wav|jpeg|gif|jpg|png|apk|exe|txt|html|zip|java|doc";
        Pattern pat = Pattern.compile("[\\w]+[\\.](" + suffixes + ")");// 正则判断
        Matcher mc = pat.matcher(url);// 条件匹配
        String substring = null;
        while (mc.find()) {
            substring= mc.group();// 截取文件名后缀名
        }
        return substring;
    }
}

效果要测试一下才知道。 测试以后发现有问题,并且调试起来很不方便须要每次把jar包发布到本地,并且服务须要重启。因此我想仍是直接在jar包中写测试代码吧。否则太花时间了。 测试以后并优化原来的代码,不必在本地生成图片文件。java

相关文章
相关标签/搜索