使用poi导出排版漂亮的excel文件

html代码:

<button class="btn btn-link" ng-model="exportExcel" ng-click="exportPreferentialOrderToExcel()" has-permission="exportPreferentialOrderToExcel">
    <span class="glyphicon glyphicon-share"></span>{{'export.preferentialOrder.ToExcel' | translate}}
</button>

js代码:

var custCode = $scope.custCode;
var orderNo = $scope.orderNo;
var preferStatus = $scope.preferStatus;
var startOperateTime = $scope.startOperateTime;
var endOperateTime = $scope.endOperateTime;
var custLeveldefineId = $scope.level;
var sort = $scope.gridOptions.sort;var url = "/sidPreferentialOrder/exportPreferentialOrderToExcel?";url+="startTime="+$("#startTime").val()+"&endTime="+$("#endTime").val();url+="&preferCode="+$("#preferentialType").val();url+="&custCode="+custCode+"&orderNo="+orderNo;url+="&endOperateTime="+endOperateTime+"&custLeveldefineId="+custLeveldefineId;url+="&preferStatus="+preferStatus+"&startOperateTime="+startOperateTime+"&sort="+sort;window.open(url);

web端action方法代码:

/**
 * 报表信息列表  不带统计样式的excel poi导出
 * @param pageHelper
 */
@RequestMapping(value="commissionReportToExcel", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public void exportCompanyWithToExcel(HttpServletRequest request, HttpServletResponse response, SidAnalyzeReportForm sidAnalyzeReportForm, PageHelper pageHelper) throws ParseException, IOException {
    String codedFileName = "报表信息列表";
    String newtitle = new String(codedFileName.getBytes("UTF-8"),"ISO8859-1");
    response.setHeader("content-disposition","attachment;filename=" + newtitle + ".xls");
    response.setContentType("application/vnd.ms-excel");
    OutputStream fOut = null;

    // 工作簿
    HSSFWorkbook wb = new HSSFWorkbook();
    String columWithMsg = "9,11,7,9,9,40,10,10,10,10,10,10,10,20";//这个字符串是列宽值 是按照列的下标0开始,比如第一列 列宽下标0开始就是7
    HSSFSheet sheet = ExportExcelUtils.setSheetBaseInfoExcel("报表信息",36,30,true,columWithMsg,wb);

    // 产生表格标题行
    HSSFRow rowm = sheet.createRow(0);
    HSSFCell cellTiltle = rowm.createCell(0);
    HSSFCellStyle columnTopStyle = ExportExcelUtils.getColumnTopStyle(wb);//获取列头样式对象
    HSSFCellStyle style = ExportExcelUtils.getStyle(wb);
    HSSFCellStyle columnNumCentStyle = ExportExcelUtils.getColumnNumCentStyle(wb); //单元格样式对象
    sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (columWithMsg.split(",").length-1)));
    cellTiltle.setCellStyle(columnTopStyle);
    cellTiltle.setCellValue(codedFileName);
    rowm.setHeightInPoints(15);

    //这个字符串是列宽值 是按照列的下标0开始,比如第一列标题 列宽下标0开始就是等级
    String columNameMsg = "客户账户,店面名称,有效会员,前期累计销量,当期累计销量,结算比例,总入款,总支出,总优惠,办公费用,会员代理,二级代理,可获总佣金,备注";
    HSSFRow row = ExportExcelUtils.setSheetTitleExcel(columNameMsg,sheet,style);
    int i = 2;
    String pageSorts = "{'availableCommission':'desc'}";
    if(null!=pageHelper.getSort() && !pageHelper.getSort().equals("") &&!pageHelper.getSort().equals("{'t.hall_id':'desc'}")){
        pageSorts = pageHelper.getSort();
    }

    if(sidAnalyzeReportForm!=null && sidAnalyzeReportForm.getHallId()==null){
        sidAnalyzeReportForm.setHallId(SecurityUtils.getCurrentHallId(request));
        if(sidAnalyzeReportForm.getHallId()!=null&&sidAnalyzeReportForm.getRole()==0){  //如果是以厅主的身份查看 直接显示该厅主下会员的数据
            sidAnalyzeReportForm.setRole(1);
            pageHelper=new PageHelper(pageHelper.getPage(),pageHelper.getPer_page());
        }
    }

    pageHelper.setSort(pageSorts);
    Response response2= listData(sidAnalyzeReportForm,pageHelper);
    PageResult<SidCommissionReportForm> resultList = (PageResult<SidCommissionReportForm>) response2.getObj();
    List<SidCommissionReportForm> commissonReportList = resultList.getContent();

    for (SidCommissionReportForm commissonReport : commissonReportList) {
        row = sheet.createRow(i + 1);
        ExportExcelUtils.createCellSetValueExcel(0,commissonReport.getName()==null?"":commissonReport.getName(),1,row);
        ExportExcelUtils.createCellSetValueExcel(1,commissonReport.getCasinoName()==null?"":commissonReport.getCasinoName(),1,row);
        ExportExcelUtils.createCellSetValueExcel(2,commissonReport.getValidCustomer()+"",1,row);
        ExportExcelUtils.createCellSetValueExcel(3,commissonReport.getLastTimeWinlose()+"",1,row);
        ExportExcelUtils.createCellSetValueExcel(4,commissonReport.getCurWinlose()+"",1,row);
        List <CmsCooperationDetail>detailList = commissonReport.getDetailList();
        String cooperationDetailMsg = "";
        if(null!=detailList && detailList.size()>0){
            for(CmsCooperationDetail detail :detailList){
                cooperationDetailMsg =cooperationDetailMsg +  CompanyTransCodeUtils.getTextMsgByCode(detail.getGameCode()) + ":"+detail.getBonusPercent() + " | ";
            }
        }
        ExportExcelUtils.createCellSetValueExcel(5,cooperationDetailMsg,1,row);
        ExportExcelUtils.createCellSetValueExcel(6,commissonReport.getTotalDeposit()+"",1,row);
        ExportExcelUtils.createCellSetValueExcel(7,commissonReport.getTotalWithdrawal()+"",1,row);
        ExportExcelUtils.createCellSetValueExcel(8,commissonReport.getTotalPreferential()+"",1,row);
        ExportExcelUtils.createCellSetValueExcel(9,commissonReport.getAdministrativeCosts()+"",2,row);
        ExportExcelUtils.createCellSetValueExcel(10,(commissonReport.getAvailableCommission()-commissonReport.getSubordinateBookmakers())+"",1,row);
        ExportExcelUtils.createCellSetValueExcel(11,commissonReport.getSubordinateBookmakers()+"",1,row);
        ExportExcelUtils.createCellSetValueExcel(12,commissonReport.getAvailableCommission()+"",1,row);
        ExportExcelUtils.createCellSetValueExcel(13,commissonReport.getRemarks()==null?"":commissonReport.getRemarks(),1,row);

        row.setHeightInPoints(30);
        int tempColumnNum = row.getPhysicalNumberOfCells();
        for (int j = 0; j < tempColumnNum; j++) {
            row.getCell(j).setCellStyle(columnNumCentStyle);
        }
        i++;
    }
//底部统计数据行 
String sumColumNo = "5,7";//显示数值的列数 比如总金额:第四列 金额数字是第五列,那么数字就要写5
String sumColumName = "总金额,金额";
String sumColumValue = amount+","+currAmount;
ExportExcelUtils.setSheetSumTotleExcel(sumColumNo,sumColumName,sumColumValue,getDownColumnTopStyle,sheet);    try {        fOut = response.getOutputStream();        wb.write(fOut);    } finally {        if (fOut != null) {            fOut.flush();            fOut.close();        }    }}//导出excel样式控制类package com.ig.common.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.IndexedColors;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hanson on 2016-08-08.
 */
public class ExportExcelUtils {

    //显示的导出表的标题
    private String title;
    //导出表的列名
    private String[] rowName ;

    private List<Object[]> dataList = new ArrayList<Object[]>();

    HttpServletResponse response;

    //构造方法,传入要导出的数据
    public ExportExcelUtils(String title,String[] rowName,List<Object[]>  dataList,HttpServletResponse response){
        this.dataList = dataList;
        this.rowName = rowName;
        this.title = title;
        this.response =  response;
    }

    /*
     * 列表首页的大title样式
     */
    public static HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short)16);
        //字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //设置背景颜色
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
        return style;
    }

    /*
     * 标题 列的样式
     */
    public static HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short)12);
        //字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //设置背景颜色
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        return style;
    }


    /*
  * 列数据信息单元格样式
  */
    public static HSSFCellStyle getColumnNumCentStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体名字
        font.setFontName("Courier New");
        //设置字体大小
        font.setFontHeightInPoints((short)11);
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(true);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        return style;
    }

    /*
 * 底部统计样式
 */
    public static HSSFCellStyle getDownColumnTopStyle(HSSFWorkbook workbook) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short)11);
        //字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("Courier New");

        font.setColor(HSSFColor.PINK.index);
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //设置背景颜色
        return style;
    }

    /**设计excel定义列数、列宽和标头信息*/
    public static HSSFSheet setSheetBaseInfoExcel(String excelName,int columWith,int rowHight,boolean fixedColum,String columWithMsg ,HSSFWorkbook wb){
        HSSFSheet sheet = wb.createSheet(excelName);
        sheet.setDefaultColumnWidth(columWith);
        sheet.setDefaultRowHeightInPoints(rowHight);
        if(fixedColum){
            sheet.createFreezePane(2,3,2,3);
        }

        String columWiths[] =  columWithMsg.split(",");
        for (int i=0;i<columWiths.length;i++){
            sheet.setColumnWidth(i,Integer.valueOf(columWiths[i])*512);
        }
        return sheet;
    }

    /**设计excel标头信息*/
    public static HSSFRow setSheetTitleExcel(String columNameMsg , HSSFSheet sheet,HSSFCellStyle style){
        String columNames[] =  columNameMsg.split(",");
        HSSFRow row = sheet.createRow(2);
        for (int i=0;i<columNames.length;i++){
            HSSFCell headCell = row.createCell(i);
            headCell.setCellValue(columNames[i]);
            headCell.setCellStyle(style);
        }
        return row;
    }

    /**创建统计行数据,创建指定列并且赋值*/
    public static void setSheetSumTotleExcel(String columNos ,String columNams,String columValues,HSSFCellStyle style,HSSFSheet sheet){
        int lastRowNum = sheet.getPhysicalNumberOfRows();
        HSSFRow row = sheet.createRow(lastRowNum + 1);
        HSSFCell cell;
        String columNoss[] =  columNos.split(",");
        String columNames[] =  columNams.split(",");
        String columValuess[] =  columValues.split(",");
        for (int i=0;i<columNoss.length;i++){

            cell = row.createCell(Integer.valueOf(columNoss[i])-1);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(columNames[i]+": ");
            cell.setCellStyle(style);

            cell = row.createCell(Integer.valueOf(columNoss[i]));
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(columValuess[i]);
            cell.setCellStyle(style);
        }
    }

    /**创建Cell 指定单元格数据类型 valueType=1代表正常单行数据   valueType=2代表换行的数据格式*/
    public static void createCellSetValueExcel(int columNo,String value,int valueType,HSSFRow row){
        HSSFCell cell;
        cell = row.createCell(columNo);
        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        if(valueType==1){
            cell.setCellValue(value);
        }else {
            cell.setCellValue(org.apache.commons.lang3.StringEscapeUtils.unescapeJava(value));
        }
    }
}