代码之家  ›  专栏  ›  技术社区  ›  Uladzislau Kaminski

使用Aspose库将分数作为文本插入到Excel

  •  0
  • Uladzislau Kaminski  · 技术社区  · 6 年前

    我需要生成列,其中一些值是分数。在这种情况下,Excel将该值显示为计算值,甚至显示为日期(用于准备屏幕截图,我手动添加了空间)。

    我认为解决方案是应用函数:

    =文本(值,“0/”0“)

    所以,我的问题是如何使用java Aspose库将函数应用于cell?这是最好的解决办法吗?

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   Amjad Sahi    6 年前

    好吧,这是MS-Excel的行为,它将分数值转换为DateTime或数值(计算)值。通过对指定单元格应用数字格式,您可以轻松地处理它。有关如何使用Aspose.cells for Java在单元格中显示分数值的参考,请参阅带有注释的示例代码。另外,请参见有关如何将公式应用于单元格的代码: 例如 示例代码:

     Workbook workbook = new Workbook();
    //Get the first worksheet (default sheet)    
    Worksheet worksheet = workbook.getWorksheets().get(0);
    Cells cells = worksheet.getCells();
    
    //Input fraction values to the cells.
    Cell cell1 = cells.get("A1");
    double val1 = 1/2d;
    cell1.putValue(val1);
    
    Cell cell2 = cells.get("A2");
    double val2 = 19/4d;
    cell2.putValue(val2);
    
    Cell cell3 = cells.get("A3");
    double val3 = 5/3d;
    cell3.putValue(val3);
    
    
    //Create a style object.
    Style style = workbook.createStyle();
    //Set the numbers formatting
    style.setCustom("# ?/?");
    
    //Apply style to the cells.
    cell1.setStyle(style);
    cell2.setStyle(style);
    cell3.setStyle(style);
    
    
    //Apply formula to a cell
    Cell cell4 = cells.get("B1");
    cell4.setFormula("=TEXT(A1,\"0/#0\")");
    
    //Even you may directly put numeric value as text value.
    Cell cell5 = cells.get("C1");
    cell5.putValue("1/2", false);
    //Note: if you double cliked in the cell, it will be converted to numeric DateTime notations.
    
    
    //Save the file
    workbook.save("f:\\files\\out1.xls");
    

    注:我在Aspose担任支持开发/传道者。