java POI excel导出自定义分页问题

以A4纸为例:

excel默认A4纸大小 =210mm×297mm,换算成excel默认单位 A4=610×850

 

1.定义列宽 width

2.获取当前列的数据长度 length = str.getBytes().length;

/*默认行高*/ 
short height = 15; 
/*页行高*/ 
double rowheight = 0;
/*定义一个list*/
List<Double> dous = new ArrayList<Double>();

/*将每一列的数据计算出行高*/
dous.add(Math.ceil((float)(length )/(sheet.getColumnWidth(cellNum)/256))*height)

/*预测行高*/
double virtualTotalHeight = rowHeight + Collections.max(dous);

/*预测行高:如果virtualTotalHeight大于A4高度则下一页开启,否则继续当前页*/
if(isPage(virtualTotalHeight)){

    HSSFRow row = sheet.createRow(rowNum);
    /*将dous中最大的值设定为行高*/
    row.setHeightInPoints(Collections.max(dous).intValue());
    /*统计总行高*/ 
    rowHeight = rowHeight + Collections.max(dous);
    /*分页符*/
    sheet.setRowBreak(rowNum);
}else{/*下一页*/
    ​
    rowHeight = 0;
    HSSFRow row = sheet.createRow(rowNum);
    /*将dous中最大的值设定为行高*/
    row.setHeightInPoints(Collections.max(dous).intValue());
    /*统计总行高*/ 
    rowHeight = rowHeight + Collections.max(dous);
​
}

 

/**
 * 判断添加一行是否大于A4纸高度
 * @param height
 * @return
 */
public static boolean isPage(double height){
    boolean flag = false;
    /*A4纵向纸高度*/
    double A4_lengthways_pageSize = 828;//纵向转换成点 (293/4.5)*12.75
    /*A4横向纸高度*/
    double A4_crosswise_pageSize = 600;//横向转换成点
    if((A4_crosswise_pageSize-height)> 30){
        flag = true;
    }else {
        flag = false;
    }
    return flag ;
}
/**
 * sheet默认设置
 * @param sheet
 */
public static  void settingDefault(HSSFSheet sheet,boolean flag){
    //设置不显示网格线
    sheet.setDisplayGridlines(false);
    //默认列宽
    sheet.setDefaultColumnWidth(8);
    /*设置打印页面为水平居中*/
    sheet.setHorizontallyCenter(true);
    /**默认行高*/
    sheet.setDefaultRowHeightInPoints((short)15);
    /*设置页边距*/
    sheet.setMargin(HSSFSheet.TopMargin,(short) 0.6);
    sheet.setMargin(HSSFSheet.BottomMargin,(short) 0.6);
    sheet.setMargin(HSSFSheet.LeftMargin,(short) 0.2);
    sheet.setMargin(HSSFSheet.RightMargin,(short) 0.2);
    /*置顶*/
    sheet.setVerticallyCenter(false);
    /*打印设置*/
    HSSFPrintSetup printSetup = sheet.getPrintSetup();
    if(flag){
        /*默认横向打印*/
        printSetup.setLandscape(true);
        /*页高设置*/
        printSetup.setFitHeight((short)610);
    }else {
        /*默认纵向打印*/
        printSetup.setLandscape(false);
        /*页高设置*/
        printSetup.setFitHeight((short)850);
    }
    //A4纸
    printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);

}
  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值