package com.sys.bus.excel.tool;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsAbstractExporterParameter;
//import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;

public class ExcelExportTool {
	@SuppressWarnings("rawtypes")
	public static ByteArrayOutputStream exportExcel(HttpServletRequest request, HttpServletResponse response, String[] jasperfilename, Map parameters, Collection[] collection)
	 throws IOException, JRException{
		  ServletContext servletContext = request.getSession().getServletContext();
	      String rptpath = servletContext.getRealPath("/jasper");
	      //parameters.put("SUBREPORT_DIR", rptpath + "/");
	      ByteArrayOutputStream oStream = new ByteArrayOutputStream();
	      JRXlsxExporter exporter = new JRXlsxExporter();
	      exporter.setParameter(
	        JRXlsAbstractExporterParameter.IS_DETECT_CELL_TYPE, 
	        Boolean.TRUE);
	      List<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
	      for (int i = 0; i < jasperfilename.length; i++) {
	    	 
	          jasperPrintList.add(JasperFillManager.fillReport(new File(
	            rptpath + "/" + jasperfilename[i]).getPath(), 
	            parameters, new JRBeanCollectionDataSource(
	            		collection[i])));
	        
	      }
	      exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, 
	        jasperPrintList);
	      exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, oStream);
	      exporter.exportReport();
	      return oStream;
   }
}


