如何在 Excel Apache POI 中设置小数点后两位的单元格宽度

How to set cell width in two decimal points in Excel Apache POI

我正在尝试获取精确到小数点后两位的固定单元格宽度值。但是生成excel文件时,单元格宽度四舍五入为我想要达到的宽度大小的整数。这可以做到吗?

  private Sheet setupSheet(XSSFWorkbook workbook) {

    Sheet xssfSheet;
    xssfSheet = workbook.createSheet("report");
    xssfSheet.getPrintSetup().setLandscape(true);
    xssfSheet.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
    xssfSheet.setMargin(Sheet.HeaderMargin, 0.1);
    xssfSheet.setMargin(Sheet.BottomMargin, 0.1);
    xssfSheet.setMargin(Sheet.LeftMargin, 0.1);
    xssfSheet.setMargin(Sheet.RightMargin, 0.1);
    xssfSheet.setFitToPage(true);
    PrintSetup ps = xssfSheet.getPrintSetup();
    ps.setFitWidth((short) 1);
    ps.setFitHeight((short) 0);
    return xssfSheet;
}

Sheet sheet = setupSheet(workbook);

int widthExcel = 10;
int width256 = (int) Math.round((widthExcel * Units.EMU_PER_POINT + 5f) / Units.EMU_PER_POINT * 256f);
            sheet.setColumnWidth(0, (int) (width256 * 1.14));
            sheet.setColumnWidth(1, (int) (width256 * 0.49));
            sheet.setColumnWidth(2, (int) (width256 * 0.85));
            sheet.setColumnWidth(3, (int) (width256 * 1.45));

            sheet.setColumnWidth(4, (int) (width256 * 0.46));
            sheet.setColumnWidth(5, (int) (width256 * 2.85));
            sheet.setColumnWidth(6, (int) (width256 * 2.02));
            sheet.setColumnWidth(7, (int) (width256 * 0.66));

            sheet.setColumnWidth(8, (int) (width256 * 0.72));
            sheet.setColumnWidth(9, (int) (width256 * 0.86));
            sheet.setColumnWidth(10, (int) (width256 * 0.75));
            sheet.setColumnWidth(11, (int) (width256 * 0.90));
 }

问题不是很清楚。但是如果你想将列宽设置为 Excel 将显示在它的 GUI 中,那么这必须使用 Sheet.setColumnWidth.

中给出的公式来完成

Excel 将列宽存储为以字符宽度的 1/256 为单位的整数值,但将它们显示为作为浮点数适合单元格的字符数。

示例:

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

class CreateExcelColumnWidth {

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

  try (Workbook workbook = new XSSFWorkbook(); 
       FileOutputStream fileout = new FileOutputStream("./Excel.xlsx") ) {

   Sheet excelSheet = workbook.createSheet();

   float widthExcel = 10.71f;
   int width256 = (int)Math.floor((widthExcel * Units.DEFAULT_CHARACTER_WIDTH + 5) / Units.DEFAULT_CHARACTER_WIDTH * 256);
   excelSheet.setColumnWidth(0, width256);

   workbook.write(fileout);
  }
 }
}

结果: