使用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++;
    }
//底部统计数据行
//导出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));
        }}
}
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();        }    }}

java 使用poi导出excel,可控制固定前2列固定标头排版,带统计数据格式的相关推荐

  1. java利用poi导出excel功能-附带图片导出

    java利用poi导出excel功能-附带图片导出 写在前面 最近刚离职,闲来无事,于是把上两家公司都有碰到过的需求但都没有去研究实现:即导出带图片的excel报表.于是就折腾了一下这个功能,研究出来 ...

  2. java中poi导出Excel表格(前台流文件接收)

    java中poi导出Excel表格,前端以流的方式接收,而非直接生成文件再下载,解决多台服务器部署后,路径地址不统一导致的下载问题. 生成Excel示例图: 2.代码说明 ① 在上次的基础上增加了底部 ...

  3. Java操作poi导出Excel自定义字体颜色

    Java操作poi导出Excel自定义字体颜色 功能介绍 POI操作Excel 第一步创建一个导出的工具类 整体定义表格字体样式 自定义表格字体样式 总结 功能介绍 Apache POI 是用Java ...

  4. Java和poi导出excel报表

    一:poi jar下载地址:点击打开链接: 二:工程截图: 三:运行效果截图: 四:源代码: Student.java: package com.poi.bean;import java.util.D ...

  5. Java使用POi导出Excel(包含图片)

    Java使用poi组件导出excel报表,能导出excel报表的还可以使用jxl组件,但jxl想对于poi功能有限,jxl应该不能载excel插入浮动层图片,poi能很好的实现输出excel各种功能, ...

  6. Excel文件首行固定前n行固定首列固定前n列固定

    1.首行首列固定 2.前n行固定 或者 前n列固定 选中第n+1行 或者 第n+1列,在冻结窗口下来选项中,选 "冻结拆分窗格"命令. 3.固定前n行前m列.(此处以n=3,m=5 ...

  7. poi导出excel 损坏_急!!!java用poi导出excel文件,打开导出的文件时报错“文件错误,数据可能丢失”...

    展开全部 两个原因: 1.你的excel模版本身有问题,可以尝试新建一个模版. 2.你的excel使用了一e68a8462616964757a686964616f31333365643662些POI不 ...

  8. java通过poi导出excel和pdf

    [背景] 由于各户的需求,所以需要增加导出excel这个功能,其实大部分系统都需要这个导出功能的,所以这里也就不详细说明具体导出的背景了O(∩_∩)O~ 干完导出excel将现有的导出pdf也进行了独 ...

  9. java使用poi导出Excel表发回浏览器或是保存到本地

    在实际工作中不可避免的会遇上统计.导出报表的工作,我自己整理了一份导出Excel代码放到这里,即为了分享知识,也是对自己的总结 首先导入依赖 <dependency><groupId ...

最新文章

  1. 北京学python去哪里好_北京想学习Python应该去哪里好
  2. IntelliJ IDEA 安装go插件
  3. libevent中的基本数据结构
  4. 安川机器人编程加电弧_安川AR2010机器人
  5. Linux下使用Speedtest测试网速
  6. Google PPRGo: 两分钟分类千万节点的最快GNN
  7. 细说CSS的transform
  8. python中常用的模块_Python中常用的模块
  9. 马蹄疾 | 2019年,是时候认真学一波 Grid 布局了
  10. 5v继电器模块实物接线_5v继电器的工作原理
  11. 谷歌李开复 我的传奇人生源于十句箴言
  12. 基于Matlab的数字水印设计实现
  13. 微信外卖小程序 怎么计算与客户的距离_3分钟搞定微信小程序类美团用户商家距离计算...
  14. POWERDNS + LVS + LAMP + NFS + MYSQL主从读写分离
  15. C++继承——以应用抽象类,求圆、圆内接正方形、圆外切正方形的面积和周长为例
  16. 通过python各种开源库,开发一个适合大部分公司测试项目框架,确定名字AutoTestProjects
  17. r720换固态硬盘后如何重装系统_换SSD学会这招后再也不用重装系统了!
  18. python音乐下载_python 音乐下载演示源代码
  19. MPI并行程序开发设计----------------------------------并行编程模型和算法等介绍
  20. TCP拥塞控制算法纵横谈-Illinois和YeAH

热门文章

  1. png,jpg转换为ico的方法
  2. 游戏引擎开发中常用的设计模式
  3. 【数据结构】测试4 串
  4. 实现单点登录SAP PO JAVA客户端(ESR/ID),无需每次下载
  5. html+css制作属于自己的头像和简介
  6. 武忠祥老师每日一题、考研题型总结
  7. 华为mate30 完全卸载google套件
  8. 数据呈现图表插件Highcharts介绍+图表联动案例
  9. jira提交bug规范
  10. uniapp 唤起京东app跳转商品详情页面和领取优惠券页面