Java中如何靈活獲取excel中的數(shù)據(jù)
在java當中獲取excel數(shù)據(jù),獲取每一列數(shù)據(jù)、每一行數(shù)據(jù)
在這里例子是將每一行數(shù)據(jù)獲取出來,并帶著表頭數(shù)據(jù)返回。
代碼:
具體實現(xiàn)邏輯在代碼注釋當中可以參見。
public static List<Map<String,Object>> test1() throws Exception{
File file = new File("C:/Users/luo_a/Desktop/數(shù)據(jù)測試.xlsx");
if (!file.exists()){
throw new Exception("文件不存在!");
}
InputStream in = new FileInputStream(file);
// 讀取整個Excel
XSSFWorkbook sheets = new XSSFWorkbook(in);
// 獲取第一個表單Sheet
XSSFSheet sheetAt = sheets.getSheetAt(0);
//默認第一行為標題行,i = 0
XSSFRow titleRow = sheetAt.getRow(0);
List<Map<String,Object>> mapList = new ArrayList<>();
// 循環(huán)獲取每一行數(shù)據(jù)
for (int i = 1; i < sheetAt.getPhysicalNumberOfRows(); i++) {
XSSFRow row = sheetAt.getRow(i);
// 讀取每一列內(nèi)容
Map<String,Object> map = new HashMap<>();
for (int index = 0; index < row.getPhysicalNumberOfCells(); index++) {
XSSFCell titleCell = titleRow.getCell(index);
XSSFCell cell = row.getCell(index);
cell.setCellType(CellType.STRING);
if (cell.getStringCellValue().equals("")) {
continue;
}
//表頭數(shù)據(jù)
String titleName = titleCell.getStringCellValue();
//單元格內(nèi)容
String valueName = cell.getStringCellValue();
//每一行的數(shù)據(jù)
map.put(titleName,valueName);
}
mapList.add(map);
}
System.out.println(JSON.toJSONString(mapList));
return mapList;
}excel例子:

代碼執(zhí)行:

將執(zhí)行結(jié)果格式化一下,更直觀。

我們只要能獲取行列數(shù)據(jù),在就可以根據(jù)自己的實際需要去實現(xiàn)自己的代碼。
總結(jié)
到此這篇關于Java中如何靈活獲取excel中數(shù)據(jù)的文章就介紹到這了,更多相關Java獲取excel數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javax.management.InvalidApplicationException的問題解決
javax.management.InvalidApplicationException是與Java Management Extensions (JMX) API相關的一個常見異常,本文主要介紹了javax.management.InvalidApplicationException的問題解決,感興趣的可以了解一下2024-08-08
mybatis-plus @DS實現(xiàn)動態(tài)切換數(shù)據(jù)源原理
本文主要介紹了mybatis-plus @DS實現(xiàn)動態(tài)切換數(shù)據(jù)源原理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07
JAVA重復調(diào)用接口導致數(shù)據(jù)不一致的問題解決
在使用JAVA進行開發(fā)時,我們經(jīng)常會遇到要調(diào)用接口來獲取數(shù)據(jù)的情況,本文主要介紹了JAVA重復調(diào)用接口導致數(shù)據(jù)不一致的問題解決,具有一定的參考價值,感興趣的可以了解一下2024-01-01
@Scheduled fixedDelayString 加載properties配置方式
這篇文章主要介紹了@Scheduled fixedDelayString 加載properties配置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

