[英]XSSFWorkbook in java
我正在使用XSSFWorkbook讀取Excel工作表數據。 當我輸入10位數字后有空格的數字時,要在保存之前刪除數字后的空格。 但是trim(),replaceAll()-所有這些都不能刪除空格。 使用currentCell.getStringCellValue()提取后,如何從字符串“ 99999999”中刪除空格。
嘗試過trim(),replaceAll()方法以及stringUtils.trim()
phoneNumber = currentCell.getStringCellValue()。replaceAll(“”,“”); System.out.println(phoneNumber);
預期是:要刪除字符串“ 99999”后的空格為“ 99999”
沒有錯誤消息,但我期望使用所有提到的方法后獲得“ 99999”但得到“ 99999”。
也許99999后面的字符不是默認的空格,而是其他水平的空白字符,例如不間斷空格。
您可以按照以下答案中所述修剪所有這樣的水平空白字符: https : //stackoverflow.com/a/28295733/3915431 。
使用apache poi
讀取Excel
完整示例:
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
class ReadExcel {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx"));
DataFormatter dataFormatter = new DataFormatter();
CreationHelper creationHelper = workbook.getCreationHelper();
FormulaEvaluator formulaEvaluator = creationHelper.createFormulaEvaluator();
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
String cellContent = dataFormatter.formatCellValue(cell, formulaEvaluator);
System.out.println("|"+cellContent+"|");
cellContent = cellContent.trim(); // trims only default white-space
System.out.println("|"+cellContent+"|");
cellContent = cellContent.replaceAll("(^\\h*)|(\\h*$)",""); // trims all horizontal white-space characters
System.out.println("|"+cellContent+"|");
}
}
workbook.close();
}
}
我嘗試使用簡單的Java類重現您的問題,但失敗了。 字符串的trim()方法工作正常。 我相信您的代碼中還有其他內容。 這是我的簡單測試。
class Scratch {
public static void main(String[] args) {
String phoneNumber = "99999999999 ";
System.out.println("before trim = " + phoneNumber.length());
phoneNumber = phoneNumber.trim();
System.out.println("after trim = " + phoneNumber.length());
}
}
結果
before trim = 12
after trim = 11
嘗試使用tostring
,然后嘗試以下代碼。
Cell currentCell;
if(currentCell.getCellTypeEnum() == CellType.STRING) {
String phoneNumber = currentCell.toString().trim();
System.out.println(phoneNumber);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.