將ireport制作的.jrxml文件轉(zhuǎn)成.html并輸出到前端

springmvc中pom依賴:

<!-- https://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports -->
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.8.0</version>
        </dependency>
        
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-pdfa</artifactId>
            <version>5.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all -->
        <dependency>
          <groupId>org.codehaus.groovy</groupId>
          <artifactId>groovy-all</artifactId>
         <version>2.5.6</version>
         <type>pom</type>
        </dependency>

數(shù)據(jù)源的配置類

package top.mau5.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.HashMap;
import java.util.Map;


@Configuration
@EnableAutoConfiguration
public class DruidDBConfig {

    private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;

//    @Value("${spring.datasource.initialSize}")
//    private int initialSize;
//
//    @Value("${spring.datasource.minIdle}")
//    private int minIdle;
//
//    @Value("${spring.datasource.maxActive}")
//    private int maxActive;
//
//    @Value("${spring.datasource.maxWait}")
//    private int maxWait;
//
//    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
//    private int timeBetweenEvictionRunsMillis;
//
//    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
//    private int minEvictableIdleTimeMillis;
//
//    @Value("${spring.datasource.validationQuery}")
//    private String validationQuery;
//
//    @Value("${spring.datasource.testWhileIdle}")
//    private boolean testWhileIdle;
//
//    @Value("${spring.datasource.testOnBorrow}")
//    private boolean testOnBorrow;
//
//    @Value("${spring.datasource.testOnReturn}")
//    private boolean testOnReturn;
//
//    @Value("${spring.datasource.poolPreparedStatements}")
//    private boolean poolPreparedStatements;
//
//    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
//    private int maxPoolPreparedStatementPerConnectionSize;
//
//    @Value("${spring.datasource.filters}")
//    private String filters;
//
//    @Value("{spring.datasource.connectionProperties}")
//    private String connectionProperties;

    @Bean     //聲明其為Bean實例
    @Primary  //在同樣的DataSource中往堡,首先使用被標(biāo)注的DataSource
    public DruidDataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

//        //configuration
//        datasource.setInitialSize(initialSize);
//        datasource.setMinIdle(minIdle);
//        datasource.setMaxActive(maxActive);
//        datasource.setMaxWait(maxWait);
//        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
//        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
//        datasource.setValidationQuery(validationQuery);
//        datasource.setTestWhileIdle(testWhileIdle);
//        datasource.setTestOnBorrow(testOnBorrow);
//        datasource.setTestOnReturn(testOnReturn);
//        datasource.setPoolPreparedStatements(poolPreparedStatements);
//        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
//        try {
//            datasource.setFilters(filters);
//        } catch (SQLException e) {
//            logger.error("druid configuration initialization filter", e);
//        }
//        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }

    @Bean
    public ServletRegistrationBean druidServletRegistrationBean() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        return servletRegistrationBean;
    }

    /**
     * 注冊DruidFilter攔截
     *
     * @return
     */
    
    @Bean
    public FilterRegistrationBean duridFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        Map<String, String> initParams = new HashMap<String, String>();
        //設(shè)置忽略請求
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.setInitParameters(initParams);
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

}

controller:

@RequestMapping(value = "report")
@RestController
public class ReportController {
    
    @Autowired
    DruidDataSource druidDataSource;
    
    @Autowired
    ReportService reportService;
    
    public static final String ROOT_PATH = "C:\\Users\\korin\\Desktop\\jaspertest\\";//本機(jī)文件保存地址
//  public static final String ROOT_PATH = "C:\\jaspertest\\";//云服務(wù)器文件保存地址
    
    @RequestMapping("uploadJrxml")
    public Map<String,Object> fileUpload(MultipartFile file) throws IllegalStateException, IOException{
        System.out.println(file.getOriginalFilename());
        Filepath filepath = new Filepath();
        filepath.setName(file.getOriginalFilename());
        filepath.setPath(ROOT_PATH+filepath.getName());
        file.transferTo(new File(filepath.getPath()));
        
        reportService.insesrt(filepath);
        Map<String,Object> map = new HashMap<>();
        map.put("msg", "ok");
        map.put("uuid", filepath.getRid());
        return map;
    }
    
    @RequestMapping("showfilelist")
    public List<Filepath> showfilelist() throws IllegalStateException, IOException{
        return reportService.select(new Filepath());
    }
    /**
     * 通過jrxml文件生成html最易,參數(shù)固定測試版
     * 
     * 在這之前應(yīng)該有個上傳jrxml文件功能肯骇,上傳到指定文件夾,存數(shù)據(jù)庫(uuid,存儲路徑等)后返回uuid
     * 
     * @param jrxml_path jrxml存放路徑
     * @param id 主鍵id
     * @return
     * @throws JRException 
     * @throws IOException 
     * @throws UnsupportedEncodingException 
     */
    @RequestMapping(value = "jrxml2html",produces = "text/html;charset=UTF-8")/* 返回格式為text/html */
    public String  jrxml2html(HttpServletRequest request,String jrxmlName,String id) throws JRException, UnsupportedEncodingException, IOException {
        
        JasperReport jasper = JasperCompileManager.compileReport(new FileInputStream(new File("C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".jrxml")));
        
        Map<String,Object> map = new HashMap<>();
        map.put("P_YHTZID", id);
        Connection conn = null;
        String str = "";
        try {
            /* 生成html文件 */
            conn = druidDataSource.getConnection();
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasper,map,conn);
            JasperExportManager.exportReportToHtmlFile(jasperPrint,"C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");
            
            /* 讀取html文件 */
            URL url = new URL("file:\\C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");
            BufferedReader br = null;
            br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while ((res = br.readLine()) != null) {
                sb.append(res.trim());
            }
            str = sb.toString();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return str;
    }
    
    //參數(shù)可變
    @RequestMapping(value = "jrxml2html_",produces = "text/html;charset=UTF-8")/* 返回格式為text/html */
    public String  jrxml2html_(HttpServletRequest request) throws JRException, UnsupportedEncodingException, IOException {
        Map<String,Object> map = getParameterMap(request);
        String jrxmlName = map.get("jrxmlName").toString();
        //,String jrxmlName,String paramId
        JasperReport jasper = JasperCompileManager.compileReport(new FileInputStream(new File("C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".jrxml")));
//      map.put("P_YHTZID", id);
        Connection conn = null;
        String str = "";
        try {
            /* 生成html文件 */
            conn = druidDataSource.getConnection();
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasper,map,conn);
            JasperExportManager.exportReportToHtmlFile(jasperPrint,"C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");
            
            /* 讀取html文件 */
            URL url = new URL("file:\\C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");
            BufferedReader br = null;
            br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while ((res = br.readLine()) != null) {
                sb.append(res.trim());
            }
            str = sb.toString();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return str;
    }
    
    //優(yōu)化后
    /**
     * @param request   參數(shù)中要帶rid(在數(shù)據(jù)庫filepath表中的rid)和相應(yīng)的報表中所需的參數(shù)名和值(如P_YHTZID=...)
     * @return
     * @throws JRException
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    @RequestMapping(value = "jrxml2html__",produces = "text/html;charset=UTF-8")/* 返回格式為text/html */
    public String  jrxml2html__(HttpServletRequest request) throws JRException, UnsupportedEncodingException, IOException {
        Filepath filepath = new Filepath();
        Map<String,Object> map = getParameterMap(request);
        filepath.setRid(map.get("rid").toString());
        String filePath = reportService.select(filepath).get(0).getPath();
        InputStream is = new FileInputStream(new File(filePath));
        JasperReport jasper = JasperCompileManager.compileReport(is);
        Connection conn = null;
        String str = "";
        filePath = filePath.replaceAll(".jrxml", ".html");//html文件路徑
        try {
            /* 生成html文件 */
            File file = new File(filePath);
            if(file.exists()) {
                file.delete();//刪除以前的html文件
            }
            conn = druidDataSource.getConnection();
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasper,map,conn);
            JasperExportManager.exportReportToHtmlFile(jasperPrint,filePath);
            
            /* 讀取html文件 */
            URL url = new URL("file:\\"+filePath);
            BufferedReader br = null;
            br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while ((res = br.readLine()) != null) {
                sb.append(res.trim());
            }
            str = sb.toString();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();//關(guān)流
                conn.close();//關(guān)閉數(shù)據(jù)庫連接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    protected Map<String, Object> getParameterMap(HttpServletRequest request) {
        return getParameterMap(request, false);
    }

    protected Map<String, Object> getParameterMap(HttpServletRequest request, boolean needNull) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String paramName : parameterMap.keySet()) {
            String[] paramValues = parameterMap.get(paramName);
            if (null != paramValues && paramValues.length > 1) {
                map.put(paramName, paramValues);
            } else if (null != paramValues) {
                String paramValue = parameterMap.get(paramName)[0];
                if (StringUtils.isNotEmpty(paramValue) || needNull) {
                    map.put(paramName, paramValue);
                }
            }
        }
        return map;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌枣察,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件燃逻,死亡現(xiàn)場離奇詭異序目,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)伯襟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門猿涨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人姆怪,你說我怎么就攤上這事叛赚。” “怎么了稽揭?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵俺附,是天一觀的道長。 經(jīng)常有香客問我溪掀,道長事镣,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任揪胃,我火速辦了婚禮璃哟,結(jié)果婚禮上唠叛,老公的妹妹穿的比我還像新娘。我一直安慰自己沮稚,他們只是感情好艺沼,可當(dāng)我...
    茶點故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蕴掏,像睡著了一般障般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上盛杰,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天挽荡,我揣著相機(jī)與錄音,去河邊找鬼即供。 笑死定拟,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的逗嫡。 我是一名探鬼主播青自,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼驱证!你這毒婦竟也來了延窜?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤抹锄,失蹤者是張志新(化名)和其女友劉穎逆瑞,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體伙单,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡获高,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了吻育。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片念秧。...
    茶點故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖扫沼,靈堂內(nèi)的尸體忽然破棺而出出爹,到底是詐尸還是另有隱情,我是刑警寧澤缎除,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布严就,位于F島的核電站,受9級特大地震影響器罐,放射性物質(zhì)發(fā)生泄漏梢为。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望铸董。 院中可真熱鬧祟印,春花似錦、人聲如沸粟害。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽悲幅。三九已至套鹅,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間汰具,已是汗流浹背卓鹿。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留留荔,地道東北人吟孙。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像聚蝶,于是被迫代替她去往敵國和親杰妓。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容