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

相關文章
相關標籤/搜索