Java 通常在產生報表,會搭配 ireport 與 Jasper。在網頁的應用程式上面,可以採用 Spring mvc 搭配 Jasper。
以下使用 spring 4.0.8 MVC 搭配 Jasper 4.5.1 搭配 JDK 7。 JDK8 要搭配 Jasper 6。
下載 Jasper
安裝完以後
檔案=>new=> report 的 blank A4 => open this template
設定名稱和位置
在左邊fields 加入 你那張表的欄位 右邊設定他屬性
然後直接拖曳進去中間隨便調位置
存檔後就可以關閉 他會產生個XXXXX.jrxml
接下來設定mvc
Jasper所需jar檔
Spring MVC 搭配 Jasper
package OOO;
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.insoft.donate.dao.XXXMapper;
@Controller
public class testreport {
final static Log logger = LogFactory.getLog(testreport.class);
@Autowired
private XXXMapper aaaMapper;
@RequestMapping("tryreport")
@ResponseBody
public void view(HttpServletRequest request,HttpServletResponse response,Model m)
{
HttpSession session = request.getSession();
try{
//資料來源
ArrayList<HashMap<String, Object>> data = aaaMapper.queryA01(null);
JRDataSource jrDataSource = new JRBeanCollectionDataSource(data);
//剛剛產生的jrxml
String jrxmlFile = session.getServletContext().getRealPath("/report/test.jrxml");
InputStream input = new FileInputStream(new File(jrxmlFile));
//Generating the report
JasperReport jasperReport = JasperCompileManager.compileReport(input);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, jrDataSource);
//產生pdf 並設定檔名
response.setHeader("Content-Disposition","inline;filename=\"gginin.pdf\"");
JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
}catch(Exception e){
e.printStackTrace();
}
}
}
http://localhost:8080/XXX/tryreport.do
第一次載入要一點時間
測試看看