简体   繁体   English

如何以英寸为单位设置固定的列宽值。 Apache POI

[英]How to set the fixed column width values in inches. Apache POI

Im setting fixed widths for the columns for the excel im creating with Apache POI.我为使用 Apache POI 创建的 excel 的列设置固定宽度。 Im having the fixed values in inches.我有以英寸为单位的固定值。 So I want to know what is the measurement that Apcahe POI is taking as a parameter.所以我想知道 Apcahe POI 作为参数的测量值是多少。 And how can I call it using the values in inches?以及如何使用以英寸为单位的值来调用它?

Sheet sheet; sheet.setColumnWidth(0, 100);

In Sheet.setColumnWidth is told that the measurement unit here is 1/256th of a character width.Sheet.setColumnWidth中被告知这里的测量单位是字符宽度的 1/256。 It also is told how exactly Excel calculates this.它还被告知Excel是如何计算这个的。

So if one wants Excel shall show column width as 10, using default font Calibri 11, then the width256 must be calculated as (int)Math.round((10*Units.DEFAULT_CHARACTER_WIDTH+5f)/Units.DEFAULT_CHARACTER_WIDTH*256f) .因此,如果想要Excel将列宽显示为 10,使用默认字体 Calibri 11,那么width256必须计算为(int)Math.round((10*Units.DEFAULT_CHARACTER_WIDTH+5f)/Units.DEFAULT_CHARACTER_WIDTH*256f)

If the need is setting the column width in inches, then first the inches should be translated to pixels and then the width256 must be calculated as (int)Math.round(widthPx/Units.DEFAULT_CHARACTER_WIDTH*256f) .如果需要以英寸为单位设置列宽,则首先应将英寸转换为像素,然后必须将width256计算为(int)Math.round(widthPx/Units.DEFAULT_CHARACTER_WIDTH*256f)

There is Units as a helper class for unit management.Units作为助手 class 用于单元管理。

Example:例子:

import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.util.Units;

class ExcelSetColumnWidth {

 public static void main(String[] args) throws Exception {

  try (Workbook workbook = new XSSFWorkbook(); 
       FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {
   Sheet sheet = workbook.createSheet();
   int widthExcel = 10;
   int width256 = (int)Math.round((widthExcel*Units.DEFAULT_CHARACTER_WIDTH+5f)/Units.DEFAULT_CHARACTER_WIDTH*256f);
   System.out.println(width256);
   sheet.setColumnWidth(0, width256);
   sheet.createRow(0).createCell(0).setCellValue("1234567890"); // Excel shows column width as 10 using default font Calibri 11

   float widthInch = 1f;
   float widthPx = widthInch * Units.PIXEL_DPI;
   width256 = (int)Math.round(widthPx/Units.DEFAULT_CHARACTER_WIDTH*256f);
   System.out.println(width256);
   sheet.setColumnWidth(1, width256);
   System.out.println(sheet.getColumnWidthInPixels(1)); // should be round 96 pixels for an inch
   sheet.createRow(1).createCell(1).setCellValue("1 inch width"); // column is 1 inch width

   workbook.write(fileout);
  }

 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM