適合新手的freeMark導出報表教程

freeMark導出報表可以通過office製作模板,然後就可以根據模板格式導出文件了,灰常的簡單方便。適合做單條或少數幾條的數據展示,如果數據多的話像列表形式可以考慮用POI,如果需要生成動態表格或者導出圖表之類的可以試試jasper。我以後也會慢慢更新這些內容的~~~

模板示例:我這裏導出的excel文件,所以用excel畫的模板,需要賦值的地方用EL表達式的方式賦值,前面的test是我的實體對象,後面對應其相應的屬性。沒有test的地方是直接傳的參數,例如第3行的年月。

畫完模板後點擊文件---另存爲,保存爲XML 點擊表格 2003(*.xml)格式。然後找到你保存的xml文件,直接修改後綴名爲.ftl,至此你的freeMark報表的模板就製作完成了~~(注意:必須是這個格式 用wps畫模板的話沒有2003的xml,導出後格式會有問題)。

接下來就是寫js頁面:

function exportExcel() {
    var dataid = {"id" : $("#dataid").val()};
    $.ajax({
        url: "http://localhost:9090/SSH/index/exportExcel.action",   //後臺地址
        data: dataid,
        success: function(res) {
                    var data = eval(res);
                    var path = data.path;    //文件路徑
                    var showA = '<a style="display:none" id="downloadB" download="導出文件名.xls" href="'+path+'">下載</a>';
                    $(showA)[0].click();
                    setTimeout(function() {   //刪除臨時文件
                        delTempFile(path);
                    }}, 2000)
                }
    });
}

//刪除臨時文件
function delTempFile(path) {
    var paths = {"path":path};
    $.ajax({
        url: "http://localhost:9090/SSH/index/delTempFile.action",
        data:paths,
    });
}

Java後臺:

package com.jialin.action;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.jialin.entity.User;
import com.jialin.service.IUserManage;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/index")
@ParentPackage("struts-default")
public class IndexAction extends ActionSupport{

        /**
        * 導出文件
        */
        @Action(value = "exportExcel", results = {@Result(name = "input", location = "/success.jsp") })
	public String top() {
        Map<String, Object> map = new HashMap<String, Object>();

        //獲取前臺傳來的參數 查詢相應的數據 
        String param = ServletActionContext.getParameter("dataid");
        JSONObject json = JSONObject .fromObject(param);
        String id = json.id;
        Session session = sessionFactory.getCurrentSession();
        List<Object> ob= session.createSQLQuery("select * from p_user where id = "+id).list();
        CustomerBean test = new CustomerBean ();
        test.setSettlementCompany(ob[0]==null ? "" : ob[0].toString());
        test.setMeterAccountName(ob[1]==null ? "" : ob[1].toString());
        test.setMeterAccountN(ob[2]==null ? "" : ob[2].toString());
        test.setBank(ob[3]==null ? "" : ob[3].toString());
        test.setAddress(ob[4]==null ? "" : ob[4].toString());

        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String curDate = timeFormat.format(new Date());
        String year = curDate.substring(0,4);
        String month = curDate.substring(5,7);

        //把實體和額外的參數放在map裏
        map.put("test",test);
        map.put("year",year);
        map.pur("month",month);

        File file = createExcel(map,"fsfphcl.ftl",filename);
    }
    
    /**
    * 創建文件
    */
    public File createExcel(Map<?, ?> dataMap, String templateName,String filename) throws IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		Configuration configuration = null;
		Map<String, Template> allTemplates =null;
		String realPath = request.getRealPath("/").replace("\\","/");
		String path = (realPath+"download\\").replace("\\","/");  //文件存放地址
		try {
			configuration = new Configuration();
			configuration.setDefaultEncoding("UTF-8");
                         //加載模板目錄
			configuration.setDirectoryForTemplateLoading(new File(realPath+"demon/template")); 

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		File file = new File(path+filename);
		Template template = configuration.getTemplate(templateName,"utf-8");//防止模板中文亂碼
		try {
			Writer w = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
			template.process(dataMap, w);
			w.flush();
			w.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return file;
	}

        /**
	 * 刪除臨時文件
	 */
         @Action(value = "delTempFile", results = {@Result(name = "input", location = "/success.jsp") })
	public void delTempFile() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String path = request.getParameter("path");
		File file = new File(path.path);
		file.delete();
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章