我在包含10多列的Excel工作表中有数据。我想将特定列数据复制到新工作表中或在控制台上显示它。我已将一个列名称添加到变量中,并检查Headers行中的每个单元格是否匹配将该列数据复制到新工作表或在光标上显示它。 我尝试使用以下代码但未获得预期的输出。请帮帮我。
代码:
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Read {
public static void main(String[] args) throws Exception{
Read read = new Read();
String x ="Address";
int columnIndex = 0;
read.extractExcelContentByColumnIndex(columnIndex,x);
}
ArrayList<String> extractExcelContentByColumnIndex(int columnIndex, String colName)
{
ArrayList<String> columndata = null;
String x ="Address";
try {
File f = new File("abc.xlsx");
FileInputStream ios = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(ios);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
columndata = new ArrayList<String>();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
System.out.println(row.getRowNum());
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
/*String temp=cell.getStringCellValue();
System.out.println(temp);*/
if(row.getRowNum() > 0){ //To filter column headings
if(cell.getColumnIndex() == columnIndex){// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
columndata.add(cell.getNumericCellValue()+"");
break;
case Cell.CELL_TYPE_STRING:
columndata.add(cell.getStringCellValue());
break;
}
}
}
}
}
ios.close();
System.out.println(columndata);
} catch (Exception e) {
e.printStackTrace();
}
return columndata;
}
}
答案 0 :(得分:0)
代码没问题,但你是按索引解析所需的列,而不是名称; 确保在参数中传递右列索引或使用列名解析列索引并保留相同的代码。