在Apache POI中设置列宽

时间:2012-07-20 06:33:27

标签: excel apache-poi

我正在使用Apache POI API编写一个Java工具,将XML转换为MS Excel。在我的XML输入中,我以磅为单位接收列宽。但Apache POI API有一个稍微奇怪的逻辑,用于根据字体大小等设置列宽。(参考API docs

是否存在将点转换为Excel预期宽度的公式?有人曾经这样做过吗?

虽然有setRowHeightInPoints()方法:(但没有列。

P.S。:输入XML是ExcelML格式,我必须将其转换为MS Excel。

5 个答案:

答案 0 :(得分:87)

不幸的是,只有来自class Sheet的{​​{3}}函数;其中width是标准字体(工作簿中的第一个字体)中的字符数,如果字体正在更改,则无法使用它。 解释了如何根据字体大小计算宽度。公式是:

width = Truncate([{NumOfVisibleChar} * {MaxDigitWidth} + {5PixelPadding}] / {MaxDigitWidth}*256) / 256

Sheet输入数据后,您始终可以使用setColumnWidth(int columnIndex, int width)

希望它有所帮助。

答案 1 :(得分:17)

请注意autoSizeColumn()的使用情况。它可以毫无问题地用在小文件上,但请注意每个列只调用一次(最后),而不是在一个没有意义的循环内调用。

请避免在大型Excel文件上使用autoSizeColumn()。该方法会产生性能问题。

我们在110k行/ 11列文件中使用它。该方法花了大约6米来自动调整所有列。

有关详细信息,请查看:How to speed up autosizing columns in apache POI?

答案 2 :(得分:10)

您也可以使用此博客中提到的util方法:Getting cell witdth and height from excel with Apache POI。它可以解决你的问题。

复制&从该博客粘贴:

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; 
  }

}

因此,当您想要获取单元格宽度和高度时,您可以使用它来获取像素值,值近似

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

答案 3 :(得分:1)

使用 Scala ,有一个漂亮的包装器 spoiwo

您可以这样做:

Workbook(mySheet.withColumns(
      Column(autoSized = true),
      Column(width = new Width(100, WidthUnit.Character)),
      Column(width = new Width(100, WidthUnit.Character)))
    )

答案 4 :(得分:0)

我用所有列和单元格的默认宽度来回答我的问题,如下所示:

int width = 15; // Where width is number of caracters 
sheet.setDefaultColumnWidth(width);