最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java?freemarker實現(xiàn)動態(tài)生成excel文件

 更新時間:2023年12月29日 10:39:59   作者:Swallow~  
這篇文章主要為大家詳細介紹了java如何通過freemarker實現(xiàn)動態(tài)生成excel文件,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下

最近做了一個動態(tài)生成excel的功能,這里記錄下部分功能,主要用到的是freemarker框架,spring就有帶,我起的demo載入了一下freemarker的jar包

一、創(chuàng)建模板

首先可以創(chuàng)建一個excel,編輯自己想要的模板,這里舉個簡單的例子

編寫好后可以保存一下,然后再保存為.xml格式的文件,就能得到模板雛形

大概是長這樣

然后根據(jù)ftl文件的語法,我們可以對模板進行改造,加入自己需要的字段

這里列舉一些常見的方式

1、普通字段填充

<Cell ss:StyleID="s17"><Data ss:Type="String">姓名</Data></Cell>
<Cell ss:StyleID="s17"><Data ss:Type="String">${(name)!}</Data></Cell>

2、日期填充,java傳入的參數(shù)類型為Date

    <Cell ss:Index="2" ss:StyleID="s17"><Data ss:Type="String">出生年月</Data></Cell>
    <Cell ss:StyleID="s17">
    <#if birth??><Data ss:Type="String">${birth?string("yyyy-MM-dd")}</Data></#if>
    </Cell>

3、switch case選擇用法

<Cell ss:StyleID="s17"><Data ss:Type="String">國籍</Data></Cell>
    <Cell ss:StyleID="s17">
    <#if certType??>
            <#switch certType> 
                <#case "A"> 
                    <Data ss:Type="String">■身份證 □外籍護照 □港澳居民來往內(nèi)地通行證</Data>
                <#break> 
                <#case "B"> 
                    <Data ss:Type="String">□身份證 ■外籍護照 □港澳居民來往內(nèi)地通行證</Data>
                <#break> 
                <#case "C"> 
                    <Data ss:Type="String">□身份證 □外籍護照 ■港澳居民來往內(nèi)地通行證</Data>
                <#break> 
                <#default> 
            </#switch>
            <#else>
                <Data ss:Type="String">□身份證 □外籍護照 □港澳居民來往內(nèi)地通行證</Data>
        </#if>
    </Cell>

4、數(shù)組對象展示

(這邊我做的這個主要是因為有動態(tài)展示的需求,如果沒有家屬信息,就不展示家屬單元格)

   <#list spouseInfos as row>
   <Row ss:AutoFitHeight="0">
    <Cell ss:MergeDown="2" ss:StyleID="s18"><Data ss:Type="String">家屬信息</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">姓名</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">${(row.name)!}</Data></Cell>
   </Row>
   <Row>
    <Cell ss:Index="2" ss:StyleID="s17"><Data ss:Type="String">關系</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">${(row.relation)!}</Data></Cell>
   </Row>
   <Row>
    <Cell ss:Index="2" ss:StyleID="s17"><Data ss:Type="String">聯(lián)系電話</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">${(row.tel)!}</Data></Cell>
   </Row>
   </#list>

這里需要注意如果使用了數(shù)組動態(tài)展示需要計算行數(shù)

可以把xml文件里的ExpandedRowCount參數(shù)進行修改,加入totalRowCount參數(shù)標記行數(shù)

在java程序中需要動態(tài)計算這個行數(shù)

 <Table ss:ExpandedColumnCount="3" ss:ExpandedRowCount="${(totalRowCount)!}" x:FullColumns="1"
   x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5">

模板制作好以后保存再修改文件格式名稱為.ftl即可

主體部分為

  <Table ss:ExpandedColumnCount="3" ss:ExpandedRowCount="${(totalRowCount)!}" x:FullColumns="1"
   x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5">
   <Column ss:Index="3" ss:AutoFitWidth="0" ss:Width="310.5"/>
   <Row>
    <Cell ss:MergeDown="2" ss:StyleID="s18"><Data ss:Type="String">基本信息</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">姓名</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">${(name)!}</Data></Cell>
   </Row>
   <Row>
    <Cell ss:Index="2" ss:StyleID="s17"><Data ss:Type="String">性別</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">${(sex)!}</Data></Cell>
   </Row>
   <Row>
    <Cell ss:Index="2" ss:StyleID="s17"><Data ss:Type="String">出生年月</Data></Cell>
    <Cell ss:StyleID="s17">
    <#if birth??><Data ss:Type="String">${birth?string("yyyy-MM-dd")}</Data></#if>
    </Cell>
   </Row>
   <Row>
    <Cell ss:MergeDown="2" ss:StyleID="s18"><Data ss:Type="String">其他信息</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">國籍</Data></Cell>
    <Cell ss:StyleID="s17">
    <#if certType??>
            <#switch certType> 
                <#case "A"> 
                    <Data ss:Type="String">■身份證 □外籍護照 □港澳居民來往內(nèi)地通行證</Data>
                <#break> 
                <#case "B"> 
                    <Data ss:Type="String">□身份證 ■外籍護照 □港澳居民來往內(nèi)地通行證</Data>
                <#break> 
                <#case "C"> 
                    <Data ss:Type="String">□身份證 □外籍護照 ■港澳居民來往內(nèi)地通行證</Data>
                <#break> 
                <#default> 
            </#switch>
            <#else>
                <Data ss:Type="String">□身份證 □外籍護照 □港澳居民來往內(nèi)地通行證</Data>
        </#if>
    </Cell>
   </Row>
   <Row>
    <Cell ss:Index="2" ss:StyleID="s17"><Data ss:Type="String">居住地址</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">${(address)!}</Data></Cell>
   </Row>
   <Row>
    <Cell ss:Index="2" ss:StyleID="s17"><Data ss:Type="String">聯(lián)系電話</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">${(tel)!}</Data></Cell>
   </Row>
   <#list spouseInfos as row>
   <Row ss:AutoFitHeight="0">
    <Cell ss:MergeDown="2" ss:StyleID="s18"><Data ss:Type="String">家屬信息</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">姓名</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">${(row.name)!}</Data></Cell>
   </Row>
   <Row>
    <Cell ss:Index="2" ss:StyleID="s17"><Data ss:Type="String">關系</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">${(row.relation)!}</Data></Cell>
   </Row>
   <Row>
    <Cell ss:Index="2" ss:StyleID="s17"><Data ss:Type="String">聯(lián)系電話</Data></Cell>
    <Cell ss:StyleID="s17"><Data ss:Type="String">${(row.tel)!}</Data></Cell>
   </Row>
   </#list>
  </Table>

二、生成文件

生成文件的主要java代碼如下

import freemarker.template.Configuration;
import freemarker.template.Template;
 
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
 
public class ExcelUtil {
 
    /**
     * 根據(jù)模板生成文件
     * @param dataMap           寫入數(shù)據(jù)
     * @param templateFilePath  模板文件路徑
     * @param outFileName       輸出文件路徑
     */
    public static void doGenerateFile(Map<String, Object> dataMap, String templateFilePath, String outFileName) {
 
        Writer out = null;
        FileOutputStream fileStream = null;
        //需要壓縮的文件,大于1個才會壓縮
 
        try {//生成合同文件
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
 
            Template t = configuration.getTemplate(templateFilePath); // 獲取模板文件
 
            // 導出文件
            File outFile = new File(outFileName);
 
            //獲取父目錄
            File fileParent = outFile.getParentFile();
            //判斷是否存在
            if (!fileParent.exists()) {
                //創(chuàng)建父目錄文件
                fileParent.mkdirs();
            }
 
            OutputStreamWriter oWriter = null;
            fileStream = new FileOutputStream(outFile);
            oWriter = new OutputStreamWriter(fileStream, StandardCharsets.UTF_8);
            out = new BufferedWriter(oWriter);
 
            // 將填充數(shù)據(jù)填入模板文件并輸出到目標文件
            t.process(dataMap, out);
        } catch (Exception e1) {
            if (fileStream != null && out != null) {
                close(fileStream, out);
            }
            System.out.println("生成文件出錯," + e1.getMessage());
        } finally {
            if (fileStream != null && out != null) {
                close(fileStream, out);
            }
        }
 
    }
 
    private static void close(FileOutputStream fileStream, Writer out) {
        try {
            fileStream.flush();
            fileStream.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println("關閉流異常," + e.getMessage());
        }
    }
 
    public static Date str2Date(String dateString) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(dateString);
            return date;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

寫個簡單的類測試一下

1、如果不需要展示List對象的數(shù)據(jù),可以存一個空數(shù)組到Map,本文為例,家屬信息為列表對象

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class TestMain {
    public static void main(String[] args) {
        //相對路徑 模板文件、輸出文件
        String templateFile = "file/temp.ftl";
        String outFileName = "file/test.xls";
        Map<String, Object> dataMap = test01();
//        Map<String, Object> dataMap = test02();
 
        try {
            ExcelUtil.doGenerateFile(dataMap, templateFile, outFileName);
        } catch (Exception e) {
            System.out.println("處理異常," + e.getMessage());
        }
    }
 
    private static Map<String, Object> test01() {
 
        Map<String, Object> dataMap = new HashMap<>();
        BigDecimal baseRow = new BigDecimal(6);
        dataMap.put("name", "張三");
        dataMap.put("sex", "男");
        dataMap.put("birth", ExcelUtil.str2Date("1990-01-10"));
        dataMap.put("certType", "A");
        dataMap.put("address", "地址詳情");
        dataMap.put("tel", "110110");
//放入一個空數(shù)組的參數(shù)避免合成的時候報錯
        List<Map<String, Object>> list = new ArrayList<>();
        dataMap.put("spouseInfos", list);
        dataMap.put("totalRowCount", baseRow);
        return dataMap;
    }
 
    private static Map<String, Object> test02() {
 
        Map<String, Object> dataMap = new HashMap<>();
        BigDecimal baseRow = new BigDecimal(6);
        dataMap.put("name", "張三");
        dataMap.put("sex", "男");
        dataMap.put("birth", ExcelUtil.str2Date("1990-01-10"));
        dataMap.put("certType", "A");
        dataMap.put("address", "地址詳情");
        dataMap.put("tel", "110110");
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> s1 = new HashMap<>();
        s1.put("name", "李四");
        s1.put("relation", "夫妻");
        s1.put("tel", "112112");
        list.add(s1);
        dataMap.put("spouseInfos", list);
        //計算展示行數(shù)
        BigDecimal subtract = baseRow.add(new BigDecimal(3));
        dataMap.put("totalRowCount", subtract);
        return dataMap;
    }
}

使用test01數(shù)據(jù)效果如圖

使用test02數(shù)據(jù)效果如圖

到此這篇關于java freemarker實現(xiàn)動態(tài)生成excel文件的文章就介紹到這了,更多相關java freemarker生成excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java后端Spring?Boot全局異常處理最佳實踐記錄

    Java后端Spring?Boot全局異常處理最佳實踐記錄

    Spring Boot通過和提供強大的異常處理機制,支持統(tǒng)一REST和頁面錯誤響應,這篇文章主要介紹了Java后端Spring?Boot全局異常處理的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2025-08-08
  • Java 鎖的知識總結及實例代碼

    Java 鎖的知識總結及實例代碼

    這篇文章主要介紹了Java 鎖的知識總結及實例代碼,需要的朋友可以參考下
    2016-09-09
  • Java多線程中的ThreadPoolExecutor解讀

    Java多線程中的ThreadPoolExecutor解讀

    這篇文章主要介紹了Java多線程中的ThreadPoolExecutor解讀,線程池中的核心線程數(shù),當提交一個任務時,線程池創(chuàng)建一個新線程執(zhí)行任務,直到當前線程數(shù)等于corePoolSize;如果當前線程數(shù)為corePoolSize,繼續(xù)提交的任務被保存到阻塞隊列中,等待被執(zhí)行,需要的朋友可以參考下
    2023-09-09
  • 關于SpringBoot自定義條件注解與自動配置

    關于SpringBoot自定義條件注解與自動配置

    這篇文章主要介紹了關于SpringBoot自定義條件注解與自動配置,Spring Boot的核心功能就是為整合第三方框架提供自動配置,而本文則帶著大家實現(xiàn)了自己的自動配置和Starter,需要的朋友可以參考下
    2023-07-07
  • 深入理解框架背后的原理及源碼分析

    深入理解框架背后的原理及源碼分析

    這篇文章來為大家深入的介紹了框架背后的原理及源碼分析,希望大家能夠更深層次的理解并使用好框架,在此與君共勉,框架雖好,但不要丟了其背后的原理
    2022-01-01
  • 10種簡單的Java性能優(yōu)化

    10種簡單的Java性能優(yōu)化

    你是否正打算優(yōu)化hashCode()方法?是否想要繞開正則表達式?Lukas Eder介紹了很多簡單方便的性能優(yōu)化小貼士以及擴展程序性能的技巧
    2017-11-11
  • 解決netty中spring對象注入失敗的問題

    解決netty中spring對象注入失敗的問題

    這篇文章主要介紹了解決netty中spring對象注入失敗的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • java使用jdbc連接數(shù)據(jù)庫簡單實例

    java使用jdbc連接數(shù)據(jù)庫簡單實例

    這篇文章主要為大家詳細介紹了java使用jdbc連接數(shù)據(jù)庫的簡單實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Java 回調(diào)機制(CallBack) 詳解及實例代碼

    Java 回調(diào)機制(CallBack) 詳解及實例代碼

    這篇文章主要介紹了 Java 回調(diào)機制(CallBack) 詳解及實例代碼的相關資料,需要的朋友可以參考下
    2017-02-02
  • spring boot項目fat jar瘦身的實現(xiàn)

    spring boot項目fat jar瘦身的實現(xiàn)

    這篇文章主要介紹了spring boot項目fat jar瘦身的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06

最新評論

丰镇市| 常山县| 五峰| 临沧市| 嫩江县| 建水县| 怀仁县| 安陆市| 嵊泗县| 平南县| 晋中市| 大冶市| 离岛区| 汪清县| 平塘县| 托里县| 汉源县| 垣曲县| 缙云县| 当涂县| 称多县| 建宁县| 鹤峰县| 宜黄县| 泉州市| 高台县| 萝北县| 班戈县| 石嘴山市| 财经| 龙门县| 德江县| 澄迈县| 特克斯县| 武夷山市| 台山市| 荆州市| 天峻县| 铁力市| 秦皇岛市| 库车县|