jxls模板导出图片

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

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包中写测试代码吧。不然太花时间了。 测试之后并优化原来的代码,没必要在本地生成图片文件。

转载于:https://my.oschina.net/miaojiangmin/blog/787462

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值