poi设置行高列宽

poi设置行高列宽

 前些天写了一篇用POI导出Excel遇到的一个怪异的问题,今天有用到了POI但是这次不适合用模板,所有的布局都是用程序来完成的。所以有遇到了些意想不到的问题。其实就两个问题,设置行高和设置列宽。
         首先我查看了POI3.0的API发现HSSFRow对象有setHeight(short height)方法,我就写了点测试代码

poi设置行高列宽    public static void main(String[] args) {
poi设置行高列宽        try {
poi设置行高列宽            HSSFWorkbook wb = new HSSFWorkbook();
poi设置行高列宽            HSSFSheet sheet = wb.createSheet();
poi设置行高列宽            HSSFRow row = sheet.createRow(0);
poi设置行高列宽            row.setHeight((short) 25);//目的是想把行高设置成25px
poi设置行高列宽            FileOutputStream fileOut = new FileOutputStream("c://a.xls");
poi设置行高列宽            wb.write(fileOut);
poi设置行高列宽            fileOut.close();
poi设置行高列宽        }
poi设置行高列宽        catch (Exception e) {
poi设置行高列宽            e.printStackTrace();
poi设置行高列宽        }
poi设置行高列宽    }

打开a.xls发现结果不是我想要的,第一行的高度都没有,没有报错说明代码有问题,为什么回没有高度呢?是不是单位不一样呢?我把row.setHeight((short) 25);改成了row.setHeight((short) 250);结果发现第一行出来了,但是这是怎么一个换算关系呢?我查看了一下导出的Excel第一行高是16像素,换算一下得出row.setHeight((short) 15.625);表示行高为一个像素,那么想设成几个像素就好做了。比如
row.setHeight((short) (15.625*n));//n为行高的像素数。
其实在API中还有一个HSSFRow 对象还有一个设置行高的函数setHeightInPoints(float height);这个函数中参数就是行高的像素数,比setHeight函数要方便多了。
行高设置完成了,接下来设置列宽

poi设置行高列宽    public static void main(String[] args) {
poi设置行高列宽        try {
poi设置行高列宽            HSSFWorkbook wb = new HSSFWorkbook();
poi设置行高列宽            HSSFSheet sheet = wb.createSheet();
poi设置行高列宽            HSSFRow row = sheet.createRow(0);
poi设置行高列宽            row.setHeight((short) 250);
poi设置行高列宽            sheet.setColumnWidth((short) 0, (short) 250);
poi设置行高列宽            FileOutputStream fileOut = new FileOutputStream("c://a.xls");
poi设置行高列宽            wb.write(fileOut);
poi设置行高列宽            fileOut.close();
poi设置行高列宽        }
poi设置行高列宽        catch (Exception e) {
poi设置行高列宽            e.printStackTrace();
poi设置行高列宽        }
poi设置行高列宽    }

接下来说说sheet.setColumnWidth((short) 0, (short) 250);
第一个参数表示要为第几列设置,第二个参数表示列的宽度,看看上面的代码按说第一行第一列的单元格形状应该是个正方形,因为宽和高都是250,但是打开导出后的Excel发现宽度没有高度大,是个长方形,查看该列的宽度仅为7个像素,看来行高和列宽的单位是不一样的,同样换一算sheet.setColumnWidth((short) 0, (short) (35.7));表示高度为一个像素,同样设置列宽的像素为sheet.setColumnWidth((short) 0, (short) (35.7*n));//n为列高的像素数。
但是目前列宽我还没找到其他的比这个更简单的函数,如果有朋友比这个更简单的希望大家多多交流。

原文地址:https://www.cnblogs.com/grj001/p/12225595.html