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

Apache poi 如何在Excel Apache POI中设置两个小数点的单元格宽度,apache-poi,width,Apache Poi,Width,我试图将固定的单元格宽度值精确到两个小数点。但是当生成excel文件时,单元格宽度被四舍五入为我想要达到的宽度大小的整数。这能做到吗 private Sheet setupSheet(XSSFWorkbook workbook) { Sheet xssfSheet; xssfSheet = workbook.createSheet("report"); xssfSheet.getPrintSetup().setLandscape(true); xssfShe

我试图将固定的单元格宽度值精确到两个小数点。但是当生成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
中显示,则必须使用中给出的公式来完成此操作

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);
  }
 }
}
结果:


默认字符宽度在我使用的poi版本中不可用。有什么解决办法吗?顺便问一下,为什么我们要在
widthExcel*单位中添加5个。这里的默认字符宽度
值?请参阅:“…+{5像素填充}…”。根据这一点,“请注意,此方法设置的宽度包括4个像素的边距填充(每边两个),以及网格线的1个像素填充(OOXML规范第3.3.1.12节)。此结果的可见字符值略小于传递给此方法的可见字符值(约为字符的1/2)”。如果我们去掉5,我们能得到我们传递的实际值吗?