Setting Column width in Apache POI

前端 未结 5 1233
闹比i
闹比i 2020-12-13 11:56

I am writing a tool in Java using Apache POI API to convert an XML to MS Excel. In my XML input, I receive the column width in points. But the Apache POI API has a slightly

5条回答
  •  情歌与酒
    2020-12-13 12:37

    You can use also util methods mentioned in this blog: Getting cell witdth and height from excel with Apache POI. It can solve your problem.

    Copy & paste from that blog:

    static public class PixelUtil {
    
        public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
        public static final short EXCEL_ROW_HEIGHT_FACTOR = 20;
        public static final int UNIT_OFFSET_LENGTH = 7;
        public static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 };
    
        public static short pixel2WidthUnits(int pxs) {
            short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH));
            widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];
            return widthUnits;
        }
    
        public static int widthUnits2Pixel(short widthUnits) {
            int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH;
            int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;
            pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));
            return pixels;
        }
    
        public static int heightUnits2Pixel(short heightUnits) {
            int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR);
            int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR;
            pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH));
            return pixels;
        }
    }
    

    So when you want to get cell width and height you can use this to get value in pixel, values are approximately.

    PixelUtil.heightUnits2Pixel((short) row.getHeight())
    PixelUtil.widthUnits2Pixel((short) sh.getColumnWidth(columnIndex));
    

提交回复
热议问题