如何在从 xls 工作表和 csv 文件中检索数据时使用“修剪”?

问题描述 投票:0回答:1

我已完成以下操作,从 xls 工作表和 csv 文件中检索代码。我尝试使用“.trim()”,但没有得到所需的输出。请告诉我哪里出错了,以便从 xls 单元格和 csv 文件中删除任何尾随空格。

 for (int rowNum = rowStart-1; rowNum < rowEnd+1; rowNum++) {
            List<String> cellTempList = new ArrayList<String>();
            Row rowObj = hssfSheet.getRow(rowNum);


            for (int col = 0; col < columnEnd; col++) {
                Cell cell = rowObj.getCell(col, Row.CREATE_NULL_AS_BLANK);
                if(cell.getCellType()==cell.CELL_TYPE_NUMERIC)
                {

                    DecimalFormat df = new DecimalFormat("#.##");
                    String cellValue=df.format(cell.getNumericCellValue());
                    cellTempList.add(cellValue.toString());
                    logger.trace(TId + " Adding cell having string to "+cellTempList);
                } else {
                    cellTempList.add(cell.toString()+"");
                }
            }

            cellDataList.add(cellTempList);


 //following to retrieve data from a csv file 
  while ((line = stream.readLine()) != null) {
            if(iteration < iteration1-1 || StringUtils.isBlank(line)) {
                iteration++;  
                continue;
            }

            //String[] splitted = line.split(",");
            String[] splitted = StringUtils.splitPreserveAllTokens(line,',');
            List<String> dataLine = new ArrayList<String>(splitted.length);
            for (String data : splitted)
                dataLine.add(data.trim());
            csvData.add(dataLine);

        }
    }
    catch (Exception e) {
        logger.error(TId + " Other Exception : " + e.getStackTrace());
        throw new Exception("-8");
    }
    finally {
        if (stream != null)
            try {
                stream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                logger.error(TId + " IOException : " + e.getStackTrace());
                throw new Exception("-8");
            }
    }
    logger.info(TId + " [Flow]:Exiting readcsvFile Method...." + csvData);
    return csvData;

}

请帮助我尝试修剪,但我没有得到所需的输出

java apache-poi hssf
1个回答
0
投票

由于 Excel 使用其他空格字符(而不是普通空格)作为不间断空格,因此 trim() 无法删除此 Unicode 空格。 您可以尝试使用正则表达式

val untrimmedData = // data extracted from excel sheet
val trimmedData = untrimmedData.replaceAll("^\\p{Z}+|\\p{Z}+$", "");
© www.soinside.com 2019 - 2024. All rights reserved.