我正在使用java(eclipse)讀取excel文件的內容並將其存儲在行對象列表中。要讀取文件,我已經在代碼中指定了文件路徑。在這種情況下,它類似於D:/Refreshed_data_daily/all_hue_posts_in_excel.xlsx。 如果代碼存在於其他某個位置,即某些其他系統中,該路徑不必相同。我該如何處理這種情況?如何從系統外部的java代碼中讀取excel文件?
公共類FacebookDataList {
private static final String FILE_NAME="D:/Refreshed_data_daily/all_hue_posts_in_excel.xlsx";
private static final String SHEET_NAME="nextv54plus_actions";
XSSFWorkbook workbook;
public static void main(String[] args){
FacebookDataList obj= new FacebookDataList();
List<FacebookFields> displayList= new ArrayList<FacebookFields>();
displayList=obj.getTheDataIntoList();
System.out.println("The Size of the list is:"+ displayList.size());
}
public List<FacebookFields> getTheDataIntoList() {
List<FacebookFields> fbList= new ArrayList<FacebookFields>();
try
{
FileInputStream fin= new FileInputStream(FILE_NAME);
workbook= new XSSFWorkbook(fin);
int sheetIndex=0;
for (Sheet sheet : workbook) {
readSheet(sheet,sheetIndex ++, fbList);}
}catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
return fbList;
}
private void readSheet(Sheet sheet, int sheetIndex , List<FacebookFields> fbList) {
if(SHEET_NAME.equals(sheet.getSheetName())){
workbook.removeSheetAt(sheetIndex);
return;
}
for (Row row : sheet){
if (row.getRowNum() > 0)
fbList.add(readRow(row));}
}
private FacebookFields readRow(Row row) {
FacebookFields record= new FacebookFields();
for (Cell cell : row) {
switch (cell.getColumnIndex()) {
case 0: record.setName(cell.getStringCellValue());
break;
case 1: record.setId(cell.getStringCellValue());
break;
case 2: record.setDate(cell.getStringCellValue());
break;
case 3: record.setMessage(cell.getStringCellValue());
break;
case 4: record.setType(cell.getStringCellValue());
break;
case 5: record.setPage(cell.getStringCellValue());
break;
case 6: record.setLikeCount(String.valueOf(cell.getNumericCellValue()));
break;
case 7: record.setCommentCount(String.valueOf(cell.getNumericCellValue()));
break;
case 8: record.setShareCount(String.valueOf(cell.getNumericCellValue()));
break;
}
}
return record;
}
public boolean checkIfListContainsData() {
List<FacebookFields> checkList= getTheDataIntoList();
return !checkList.isEmpty() ;
}
}
哪裏是代碼時
改變功能到
並使用文件路徑? – pelumi
正確提及您的查詢。什麼樣的應用程序是獨立的還是Web應用程序?該文件位置是否會動態變化? –