简体   繁体   English

如何在Java中将Excel行转换为字符串值?

[英]how to convert Excel row to string value in Java?

Is there a direct built-in function in Java POI to convert an Excel row to string? Java POI中是否有直接内置函数将Excel行转换为字符串? I have tried "row.toString()" but it returned the memory location of the row. 我已经尝试过“ row.toString()”,但是它返回了行的内存位置。

You can iterate over Cells, 您可以遍历单元格,

       Row row = (Row) rows.next();
        Iterator cells = row.cellIterator();

     while (cells.hasNext()) {
      Cell cell = (Cell) cells.next();
...
}

And for retrieve a string of a cell you can use : 为了检索单元格的字符串,您可以使用:

cell.getStringCellValue()
     XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File("path")));

        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
    Iterator<Cell> cellIterator = row.cellIterator();
          while (cellIterator.hasNext()) 
            {
               Cell cell = cellIterator.next();
                switch (evaluator.evaluateInCell(cell).getCellType()) 
                {                  
                    case Cell.CELL_TYPE_NUMERIC:
                        double a = cell.getNumericCellValue();
                        break;
                    case Cell.CELL_TYPE_STRING:
                        String val = cell.getStringCellValue();
                        break;
                 }
            }

You can try using the Files class in java. 您可以尝试在Java中使用Files类。 It has methods for eg 它具有例如

Files.lines(Path path)

that takes in a path and returns a Stream. 它接受路径并返回流。 With a stream you can split the rows and apply your methods. 使用流,您可以拆分行并应用您的方法。 You can take a look at its API for its other methods whichever may be more applicable. 您可以查看其API的其他方法,以较合适的方法为准。

https://docs.oracle.com/javase/9/docs/api/java/nio/file/Files.html https://docs.oracle.com/javase/9​​/docs/api/java/nio/file/Files.html

Dont iterate through all Cells/Lines, just pick your certain Cell by following: 不要遍历所有单元格/行,只需按照以下步骤选择您的特定单元格即可:

int x = 5;
int y = 8;   
// open your File
Workbook wb = new XSSFWorkbook(file);
// Get your excel sheet nr. 1
XSSFSheet sheet = Workbook.getSheetAt(0);
// get your Row from Y cordinate
Row yourRow = sheet.getRow(y);
// get your Cell from X cordinate
Cell yourCell = cell = yourRow.getCell(x);
// be sure that the pointingCell is an String or else it will catch Exception.
String cellString = cell.getStringCellValue();

All the code you need to do this is given in the Apache POI documentation , specifically iterating over rows and cells and getting the cell contents . Apache POI文档中给出了执行此操作所需的所有代码,特别是遍历行和单元格获取单元格内容 Reading the documentation often helps! 阅读文档通常会有所帮助!

Assuming you want to do something simple like join all the cells together with commas (note - not a good way to generate a CSV as you also need to escape things!) you'd do something like this: 假设您想做一些简单的事情,例如将所有单元格与逗号连接在一起(请注意,这不是生成CSV的好方法,因为您还需要转义!),您可以执行以下操作:

// Load the file, get the first sheet
Workbook wb = WorkbookFactory.create(new File("input.xls"));
Sheet sheet = wb.getSheetAt(0);

// To turn numeric and date cells into friendly formatted strings
DataFormatter formatter = new DataFormatter();

// Process every row
for (Row row : sheet) {
   StringBuffer text = new Stringbuffer();
   // Turn each cell into a string, and append
   for (Cell : row) {
      if (! text.isEmpty()) { text.append(", "); }
      text.append(formatter.formatCellValue(cell));
   }

   // TODO Do something useful with the string
   String rowAsText = text.toString();
}

// Tidy up
wb.close();

You could use the java8 foreach to get maybe a more convenient code: 您可以使用java8 foreach获得也许更方便的代码:

try (
    InputStream inputStream = RowToString.class.getResourceAsStream("excel.xlsx");
    Workbook workbook = WorkbookFactory.create(inputStream);
) {
    Sheet sheet = workbook.getSheetAt(0);
    List<String> rows = new ArrayList<>();
    sheet.forEach(row -> {
        StringJoiner joiner = new StringJoiner("|");
        row.forEach(cell -> joiner.add(cell.toString()));
        rows.add(joiner.toString());
    });

    rows.forEach(System.out::println);
}

The StringJoiner is a good choice to concatenate the values. StringJoiner是连接值的好选择。 For get the cell values, the toString works fine. 为了获取单元格值, toString可以正常工作。 The toString will get the proper value of any cell type. toString将获取任何单元格类型的正确值。 The only problem is that the toString won't resolve a formula, it will get the formula itself. 唯一的问题是toString不会解析公式,它将获取公式本身。 But you can adapt the code for your own necessity. 但是您可以根据自己的需要修改代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM