以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);

}

更多推荐

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