【问题标题】:How to set the fixed column width values in inches. Apache POI如何以英寸为单位设置固定的列宽值。阿帕奇 POI
【发布时间】:2020-01-21 03:16:27
【问题描述】:

我为使用 Apache POI 创建的 excel 的列设置固定宽度。我有以英寸为单位的固定值。所以我想知道 Apcahe POI 作为参数的测量值是多少。以及如何使用以英寸为单位的值来调用它?

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

【问题讨论】:

    标签: java apache-poi column-width


    【解决方案1】:

    Sheet.setColumnWidth 中被告知这里的测量单位是字符宽度的 1/256。它还被告知Excel 是如何计算的。

    所以如果想要Excel 显示列宽为10,使用默认字体Calibri 11,那么width256 必须计算为(int)Math.round((10*Units.DEFAULT_CHARACTER_WIDTH+5f)/Units.DEFAULT_CHARACTER_WIDTH*256f)

    如果需要以英寸为单位设置列宽,则首先应将英寸转换为像素,然后width256 必须计算为(int)Math.round(widthPx/Units.DEFAULT_CHARACTER_WIDTH*256f)

    Units作为单元管理的辅助类。

    例子:

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

    【讨论】:

    • 感谢您的回答。我似乎无法从 Units 助手类中解析 DEFAULT_CHARACTER_WIDTH
    • @dinesh alwis:你使用的是什么apache poi 版本?见这里:poi.apache.org/apidocs/dev/….
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多