如何将2行标题从'xls'文件转换为单行标题?

时间:2018-02-12 17:24:41

标签: java excel string if-statement stringbuffer

我正在尝试从excel文件创建一个标头,该文件在两个不同的行上有表头。我必须从这两个中创建一个标题行。

我正在关注的方法是在第一个标头上附加一个@并尝试用第二个标头值替换它。

我的excel文件看起来像这样

 Bank   Positive    Name of    Local Approah
 Value  Customer    Civilian   Remote

 //some data

这是我使用的代码

public List<String> processSheet(Sheet sheet) {
    ActivityLauncher.logConsoleMsg("Processing sheet " + sheet.getSheetName() + " started");
    List<String> rows = new ArrayList<String>();
    Iterator<Row> rowIterator = sheet.iterator();
    List<String>firstHeader = new ArrayList<String>();
    List<String>secondHeader =  new ArrayList<String>();
    List<String>finalHeader = new ArrayList<String>();

    while (rowIterator.hasNext()) {
        Row currentRow = rowIterator.next();
        StringBuilder row = new StringBuilder();
        for (int i = 0; i < currentRow.getLastCellNum(); i++) {
            if(currentRow.getRowNum()==0 || currentRow.getRowNum()==1 || currentRow.getRowNum()==3 || currentRow.getRowNum()==2) {  
                continue;
            } else {
                Cell currentCell = currentRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                String cellValue = excelManager.evalCell(currentCell);

                //inserting the alternate row into the text file to make a continues header
                if(currentCell.getRowIndex()==4 ) {
                    if(cellValue.equals("Local Risk")) {
                        row.append(cellValue);
                        row.append("@");
                        break;
                    } else {
                        row.append(cellValue);
                        row.append("@");
                    }
                }
                if(currentCell.getRowIndex()==5) {
                    if(cellValue.equals("rating")) {
                        row.append(cellValue);
                        row.append("@");
                        break;
                    } else {
                        int pos = row.indexOf("@");
                        if(pos >=0) {
                            row.replace(pos, 1, cellValue);
                        }
                    }
                }
            }
        }
        if (!row.toString().isEmpty()) {
            rows.add(row.toString());
        }
    }
    ActivityLauncher.logConsoleMsg("Processing sheet " + sheet.getSheetName() + " completed");
    return rows;
}

目前,我得到了这个输出:

Bank@Positive@Name of@Local Approah@
Value   Customer    Civilian   Remote 

但我的目标是制作

Bank Value Positive Customer Name of Civilian Approach Remote 

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

row.toString().replaceAll("@", cellValue);无效,因为在调用toString之后获得的字符串以及随后的替换将被删除并收集垃圾。

如果您想进行就地替换,请使用indexOfreplace(int,int,String)

int pos = row.indexOf("@");
if (pos >= 0) {
    row.replace(pos, pos+1, cellValue);
}

此外,当您从'@'字符的插入中扫描不同的行时,必须进行替换,因此当您离开时,您需要确保第4行中的StringBuilder“幸存”到第5行。为了使这个工作在循环外声明row,只有在当前行不等于4时才用新的替换:

StringBuilder row = new StringBuilder();
while (rowIterator.hasNext()) {
    Row currentRow = rowIterator.next();
    ...
    if (currentCell.getRowIndex() == 4) {
        continue;
    }
    if (!row.toString().isEmpty()) {
        rows.add(row.toString());
        row = new StringBuilder();
    }
}

答案 1 :(得分:1)

小提琴的外部链接:

Here is a fiddle我使用的硬编码数据使用的算法与下面的例子完全相同。

对于标题,您最好使用这两行创建一个列表,并在完成后附加字符串。

请尝试使用此代码:

public List<String> processSheet(Sheet sheet) {
    List<String> headers = new ArrayList<>();
    Iterator<Row> rowIterator = sheet.iterator();
    int rowCnt = 0;
    while (rowIterator.hasNext()) {
        Row currentRow = rowIterator.next();
        for (int i = 0; i < currentRow.getLastCellNum(); ++i) {
            Cell currentCell = currentRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            String cellValue = excelManager.evalCell(currentCell);

            headers.add(rowCnt + (i * (rowCnt+1)), cellValue);
        }
        ++rowCnt;
    }

    return headers;
}

此算法适用于任意数量的行和任意数量的列,只要每行的列数相同即可。 here's a fiddle具有遵循相同算法的硬编码示例数据。完成此操作后,您可以将字符串2加2(如果标题为3行高,则为3乘3)。像这个算法的东西应该没问题:

private static List<String> appendStrings(List<String> original, int group) throws Exception {
    if (original.size() % group == 0) {
        List<String> newList = new ArrayList<>();
        for (int i = 0; i < original.size(); i += group) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < group; ++j) {
                if (sb.length() > 0) {
                    sb.append(" ");
                }
                sb.append(original.get(i + j));
            }
            newList.add(sb.toString());
        }

        return newList;
    } else {
        throw new Exception("MyClass::appendStrings() ---> the group value must be a factor of the size of the original list");
    }
}

如果您的行可能包含空单元格,并且您不希望添加空字符串,但仍希望遵守该顺序,则需要在生成列表后删除数据。像这样:

public List<String> processSheet(Sheet sheet) {
    /*... same code as previous example ...*/

    // the following removes all "" or null values
    while(headers.remove(null) || headers.remove("")){}

    return headers;
}