【问题标题】:Preserve Single Quote Prefix of Cell Value of excel using Apache POI使用Apache POI保留excel单元格值的单引号前缀
【发布时间】:2021-02-16 20:41:41
【问题描述】:

目前我正在从我的工作表中读取 excel 值 但它忽略了单元格值中的“'”

Expected output- 'Testing
Actual output  -  Testing

从excel读取时如何显示单个qoute

package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelDataConfig {

    XSSFWorkbook wb;
    XSSFSheet sheet1;

    public ExcelDataConfig(String excelPath) throws IOException {
        File src = new File(excelPath);
        FileInputStream fis = new FileInputStream(src);
        wb = new XSSFWorkbook(fis);
        
        
    }

    public String getData(int sheetNumber, int row, int column) {
        sheet1 = wb.getSheetAt(sheetNumber);
        String data = sheet1.getRow(row).getCell(column).getStringCellValue();
        return data;

    }
}

我的测试课

ExcelDataConfig excel = new ExcelDataConfig(System.getProperty("user.dir") + "/src/test/resources/testData/TestData.xlsx");
System.out.println("String with double quotes=" +excel.getData(0, 0, 0));

    

【问题讨论】:

    标签: java excel selenium apache-poi


    【解决方案1】:

    前导单引号字符' 是 Excel 中的一个特殊字符,它告诉它逐字处理其内容。我知道的最常见的用途是告诉它不要通过删除前导零来格式化数值。

    当您在 Excel 中输入前缀为 ' 的值时,请注意引号如何仅出现在编辑字段中,而不是在工作表中显示的单元格中。

    在幕后,quotePrefix 值与值本身分开存储。 例如,设置'Testing 将导致 只是Testing,而OOXML 中的quotePrefix=true

    如此技术性,如此出色,POI 正确报告了 ,它为您提供 Excel 显示的值,即 Testing。 要使单引号出现在 POI 中,请访问属性 CellStyle.getQuotePrefixed() 并手动添加。

    所以在你的例子中你可以尝试:

    Cell cell = sheet1.getRow(row).getCell(column);
    String data = cell.getStringCellValue();
    if(cell.getCellStyle().getQuotePrefixed()) {
        data = '''+data;
    }
    return data;
    

    这样,您可能会(取决于用例)遇到有时需要前缀而在其他情况下不需要前缀的问题,尤其是在您无法控制输入 Excel 的情况下。可以说,通过添加第二个来转义 Excel 本身中的单引号可能“更正确”。因此,在 Excel 中,您将输入 ''Testing。这将确保 Excel 和 POI 都报告所需的 'Testing 值,而无需使用上述代码。

    【讨论】:

      【解决方案2】:

      是的,它会忽略单引号,因为 xls 单元格中的单引号实际上是按原样接受数据的快捷方式。 因此,如果您要存储“Hello Superman”,请将其存储为“Hello Superman”,它将被正确读取为“Hello Superman”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-12
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-30
        • 1970-01-01
        相关资源
        最近更新 更多