二、点击导出按钮创建excle写入内容后下载功能实现

/*涉及的jar包
1)biframework.jar
用于实现分页功能
2)poi-3.7-20101029.jar:读取、创建、修改excle、word、ppt的Java API
Apache POI是创建和维护操作各种符合Office Open XML(OOXML)标准和微软的OLE复合文档格式(OLE2)的Java API。
用它可以使用Java读取和创建,修改MS Excel文件.而且,还可以使用Java读取和创建MS Word和MSPowerPoint文件。
Apache POI 提供Java操作Excel解决方案(适用于Excel97-2008)
HSSF:是POI工程对Excel 97(-2007)(.xls)文件操作的纯Java实现。
XSSF:是POI工程对Excel 2007 OOXML (.xlsx)文件操作的纯Java实现。
HWPF:提供读写Microsoft Word DOC格式档案的功能。
HSLF:提供读写Microsoft PowerPoint格式档案的功能。
HDGF:提供读Microsoft Visio格式档案的功能。
HPBF:提供读Microsoft Publisher格式档案的功能。
HSMF:提供读Microsoft Outlook格式档案的功能。
*/
1、查询结果导出到excle功能实现
<input type="button" value="数据导出" onclick="monitRulesExportexcel()"/>
2、js函数

function monitRulesExportexcel() {
            var ruleDeclaration =document.getElementById("ruleDeclaration").value;// 规则说明
            var dealType = document.getElementById("dealType").value;// 类型
            var url= document.getElementById("monitRulesListFrom").action = "monitRulesAction.do?action=exportExcel&ruleDeclaration="
                    + ruleDeclaration
                    + "&dealType="
                    + dealType;
            document.getElementById("monitRulesListFrom").submit();
        }
View Code

3、MonitRulesAction中的exportExcel方法

public ModelAndView exportExcel (HttpServletRequest request,
               HttpServletResponse response,Object obj) throws Exception{
        response.setContentType("text/html;UTF-8");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("GBK");
        Paper paper = new Paper() ;
        String pageDirection = Tools.nulltostring((String) request.getParameter("pageDirection")) ;
        String currentPage = Tools.nulltostring((String) request.getParameter("currentPage"));
        ruleDeclaration=Tools.nulltostring(request.getParameter("ruleDeclaration"));
        dealType = Tools.nulltostring(request.getParameter("dealType"));
        
        Map map=new HashMap();
        map.put("ruleDeclaration", ruleDeclaration);
        map.put("dealType", dealType);
        map.put("ruleDeclaration", ruleDeclaration);
        map.put("dealType", dealType);
        
        List<Map<String,Object>> monitRulesList=service.getMonitRulesDataList(map,paper, currentPage,pageDirection, 5);
        System.out.println(monitRulesList.size());
        String[] titles=new String[]{"规则编码","金额","次数","统计天数","规则说明","类型","特征","标识"};
        //创建名称为:excle文件对象并设定该excle的sheet页对象名为“监测规则数据”
        HSSFWorkbook book=ExportExcel.creatWorkBook("监测规则数据");
        //获取"可疑交易监测规则数据"sheet对象
        HSSFSheet sheet=book.getSheet("监测规则数据");
        
        //创建表头行
        HSSFRow row0 = sheet.createRow(0);
        //创建表头样式
        HSSFCellStyle titletyle=ExportExcel.creatTitleStyle(book);
        //给excle中第一行写入:列明信息
        for (int i = 0; i < titles.length; i++) {
              //createCell:创建单元格
              HSSFCell cell = row0.createCell(i);//创建第一行
              cell.setCellValue(titles[i]);
              cell.setCellStyle(titletyle);
        }    
        //设置表头:所占行和列数信息
        for (int i = 0; i <titles.length; i++) {
            ExportExcel.mergeCell(sheet, 0, 1, i, i);//起始行、结束行、起始列、结束列
        }
        ExportExcel.exportExcelForSupplier(response, monitRulesList,MonitRulesExportBean.class,sheet.getSheetName(),book,2);
        return null;
    }
View Code

4、调用生成excle的工具类:ExportExcle.java

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;

/**
 * Excel 导出公共类
 */
public  class  ExportExcel {
    //创建一个WOOKBOOK &SHEET
    public static HSSFWorkbook creatWorkBook(String filename){
        HSSFWorkbook workbook = new HSSFWorkbook();//创建Excel文件
         HSSFSheet sheet = workbook.createSheet(filename);//创建Excel的一个sheet
        
         return workbook;
    }
    //单元格样式
    public  static HSSFCellStyle creatCenterStyle(HSSFWorkbook workbook){
         HSSFCellStyle centerstyle = workbook.createCellStyle();  
         centerstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//     上下居中
         centerstyle.setWrapText(true);//设置自动换行
         centerstyle.setFillBackgroundColor((short)13);
         return centerstyle;
    }
    //表头样式
    public  static HSSFCellStyle creatTitleStyle(HSSFWorkbook workbook){
        HSSFCellStyle titletyle = workbook.createCellStyle();
         HSSFFont font = workbook.createFont();
         font.setColor(HSSFColor.RED.index);
        
         titletyle.setFont(font);
         titletyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
         titletyle.setWrapText(true);
        return titletyle;
        
    }
    //导出方法
    public static void exportExcelForSupplier(HttpServletResponse response,List ls,Class c,String sheetname,HSSFWorkbook workbook,int index)throws Exception{
        String filePath = null;
        File excelFilePath = null;
        String excelFileName = null;
        File tempExcelFile = null;
        OutputStream ouputStream=null;
            String fileName = "aaaa";
            response.reset();// 清空输出流
            response.setContentType("application vnd.ms-excel;charset=utf-8");    
            response.setHeader("Content-disposition", "attachment;filename=auditdate.xls");            
             HSSFSheet sheet=workbook.getSheet(sheetname);
             HSSFCellStyle centerstyle=ExportExcel.creatCenterStyle(workbook);
              Field[] fs = c.getDeclaredFields();
             //resultList是列表集合
             for (int i= 0; i<ls.size();i++) {
                 HSSFRow row = sheet.createRow(i+index);//创建行
                  row.setRowStyle(centerstyle);
                  Object kybean=ls.get(i);
                   for (int k = 0;k<fs.length;k++){
                       Field f = fs[k];
                        HSSFCell cells = row.createCell(k);
                        f.setAccessible(true);
                        cells.setCellValue((String)f.get(kybean));
                        cells.setCellStyle(centerstyle);
                   }
             }
                    ouputStream = response.getOutputStream();
//                    BufferedOutputStream bo=new BufferedOutputStream(ouputStream,12);
//                    workbook.write(bo);
                    workbook.write(ouputStream);    
                    ouputStream.flush();    
                    ouputStream.close();

            }
    //合并单元格        
     public static int mergeCell(HSSFSheet sheet,int firstRow,int lastRow,int firstColumn,int lastColumn){
          return sheet.addMergedRegion(new CellRangeAddress(firstRow,lastRow,firstColumn,lastColumn));
     }
    public static void main(String[] args) {
        List<List<Object>> ls=new ArrayList<List<Object>>();
        List<Object> list=new ArrayList<Object>();
        list.add("sdfd");
        list.add(111);
        ls.add(list);
        list.add(423423);
        list.add(0.444);
        ls.add(list);
        Object[]obj=ls.get(0).toArray();
        Object[]obj1=ls.get(1).toArray();
    }
}
View Code

更多关于excle生成方法可参看博文

https://www.cnblogs.com/jiarui-zjb/p/9440797.html

https://www.cnblogs.com/jiarui-zjb/p/9439609.html

posted @ 2017-09-23 10:23  爱笑的berg  阅读(955)  评论(0编辑  收藏  举报