从使用Apache POI它存在于不同的行两列提取共同的价值观 [英] Extracting common values from two columns which exists in different rows using apache poi
问题描述
我使用Apache POI用于读取和写入值擅长用java文件。现在假设我有三个列三行,我有值
I am using the apache poi for reading and writing values to excel file with java. Now suppose I have three columns and three rows, i have values as
{row1, column1} = data1
{row1, column2} = data1
{row2, column1} = data2
{row2, column2} = data4
{row3, column1} = data3
{row3, column2} = data2
现在,我已存储的所有这些值在两个字符串'a'和'B'列1和第2列分别。我需要输出,均符合以下code两列常见的:
Now, I have stored all these values in two strings 'a' and 'b' for column 1 and column 2 respectively. I need to output which are common in both columns with following code:
for(int i=2; i<=rows_count;i++)
{
String a = datatable1.getCellData("temp", 1, i );
//System.out.println("a is " + a);
String b = datatable1.getCellData("temp", 3, i);
//System.out.println("b is " + b);
if(a.equals(b))
{
System.out.println(b);
}
}
有了这个我得到的输出为数据1只而不是数据2,因为这些都是在不同的行。任何想法如何解决这个问题。谢谢!
With this I am getting the output as 'data1' only but not 'data2' as these are in different rows. Any ideas how to resolve this. Thanks!
推荐答案
我相信你问的是如何报告哪些多次出现在文件的部分中的所有单元格值。假设如此,最简单的事情可能是
I believe what you're asking is how to report all cell values which appear more than once in a section of the file. Assuming so, simplest thing is probably
Set<String> alreadySeen = new HashSet<String>();
Set<String> duplicates = new HashSet<String>();
DataFormatter fmt = new DataFormatter();
// Update these as per your requirements
int firstRowToCheck = 0;
int lastRowToCheck = Math.min(3, sheet.getLastRowNum());
int firstColumnToCheck = 0;
int lastColumnToCheck = 1;
// Loop over the rows and cells of interest
for (int rn=firstRowToCheck; rn <= lastRowToCheck; rn++) {
Row r = sheet.getRow(rn);
if (r == null) {
// No cells in this row have any values
} else {
for (int cn=firstColumnToCheck; cn <= lastColumnToCheck; cn++) {
Cell c = row.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null) {
// No value for this cell
} else {
String value = fmt.formatCellValue(c);
if (alreadySeen.contains(value)) {
// Duplicate!
duplicates.put(value);
} else {
// First time this has been seen
alreadySeen.put(value);
}
}
}
}
}
// Report duplicates
for (String dup : duplicates) {
System.out.println(dup);
}
这篇关于从使用Apache POI它存在于不同的行两列提取共同的价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!