如何使用 POI 读取 Excel 文件的空单元格
2022-09-04 07:14:51
我尝试使用POI读取Excel文件,然后我想将该数据放入.JTable
这是excel文件,
如您所见,上表中有两个空单元格,一旦我将上述数据读入我得到的结果,JTable
在我的,空单元格已移动到错误的位置,我使用以下代码来获得此结果,请帮助我获得正确的结果,JTable
private XLSContainer xLSContainer;
Vector cellVectorHolder;
private int noOfCells=0;
public XLSContainer readXLS(XLSFile xLSFile) {
cellVectorHolder = new Vector();
try {
FileInputStream inputStream = new FileInputStream(xLSFile.getFileName());
POIFSFileSystem pOIFSFileSystem = new POIFSFileSystem(inputStream);
HSSFWorkbook hSSFWorkbook = new HSSFWorkbook(pOIFSFileSystem);
HSSFSheet hSSFSheet = hSSFWorkbook.getSheetAt(0);
Iterator rowIter = hSSFSheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow row = (HSSFRow) rowIter.next();
if(row.getRowNum()==0){
noOfCells = row.getLastCellNum();
}
Iterator cellIter = row.cellIterator();
Vector cellStoreVector = new Vector();
while (cellIter.hasNext()) {
HSSFCell hSSFCell = (HSSFCell) cellIter.next();
//System.out.println(hSSFCell.getCellNum());
cellStoreVector.addElement(hSSFCell);
}
cellVectorHolder.addElement(cellStoreVector);
}
} catch (Exception e) {
e.printStackTrace();
}
feedXLSContainer();
return xLSContainer;
}//readXLS
private void feedXLSContainer() {
xLSContainer = new XLSContainer();
for (int i = 0; i < cellVectorHolder.size(); i++) {
Vector cellStoreVector = (Vector) cellVectorHolder.elementAt(i);
Vector item = new Vector();
for (int j = 0; j < cellStoreVector.size(); j++) {
HSSFCell cell = (HSSFCell) cellStoreVector.elementAt(j);
item.add(cell.toString());
}
if (i == 0) {
xLSContainer.addHeader(item);
} else {
xLSContainer.addRow(item);
}
}
}
我上面所做的是将标题和数据行放入一个名为的类中的单独向量中,然后将这些向量放入.xLSContainer
JTable
这是我在更多的谷歌搜索后如何解决它:-)
private XLSContainer xLSContainer;
public XLSContainer readXLS(XLSFile xLSFile) {
try {
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
Workbook workbook = Workbook.getWorkbook(new File(xLSFile.getFileName()), ws);
Sheet s = workbook.getSheet(0);
System.out.println("Sheet Content::" + s.getName());
readDataSheet(s);
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
return xLSContainer;
}
private void readDataSheet(Sheet s) {
xLSContainer = new XLSContainer();
int noOfRows = s.getRows();
int noOfCols = s.getColumns();
for (int i = 0; i < noOfRows; i++) {
Vector item = new Vector();
for (int j = 0; j < noOfCols; j++) {
if (s.getCell(j, i).getContents() == "") {
item.add("");
} else {
item.add(s.getCell(j, i).getContents());
}
}
if (i == 0) {
xLSContainer.addHeader(item);
}else{
xLSContainer.addRow(item);
}
}
}