jasper還原成jrxml

利用jasperreport開發報表時,開發模式存檔為副檔名jrxml,再編譯成jasper檔案,提供程式呼叫使用。

如果不小心jrxml遺失或格式損壞了,要怎麼辦呢?jasper跟jrxml其實是可逆的,也就是jasper可以還原成jrxml,只需要簡單的程式碼,不過特別需要注意的是,如果報表裡有用到其它第三方的library,在反譯時也需要一起加入。

jasperToJRxml




程式碼如下:

package com.yslifes;
import java.io.File;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.xml.JRXmlWriter;
public class JasperToJRXML {
	//來源路徑
	public final static String sourcefolder = "D:/jasper/";
	//目地路徑
	public final static String destinationfolder = "D:/jrxml/"; 
	
    public static void main(String[] args) {
    	
    	
        File folder = new File(sourcefolder);
        for (final File fileEntry : folder.listFiles()) 
        {
                if(fileEntry.getName().lastIndexOf(".jasper")==fileEntry.getName().length()-7)
                {
                	doRestore(fileEntry.getName());
                
                }
                	
        }
        
    }
    
    public static void doRestore(String name)
    {
    	System.out.println(name+";"+(name.substring(0,name.length()-7)+".jrxml"));
    	String sourcePath =  sourcefolder+name;// jsper檔案位置
        String destinationPath = destinationfolder+name.substring(0,name.length()-7)+".jrxml"; // 要產出jrxml檔案的位置
        try {
            @SuppressWarnings("deprecation")
            JasperReport report = (JasperReport) JRLoader.loadObject(sourcePath);
            JRXmlWriter.writeReport(report, destinationPath, "UTF-8");
        } catch (JRException e) {
            e.printStackTrace();
        }
    }
}

原始碼下載

 

發表迴響