Created
January 15, 2024 13:13
-
-
Save akashdktyagi/5d33e0ef4e3a719e9f8f7009b8b0e17c to your computer and use it in GitHub Desktop.
Java Code to Read the Excel file and return a hash map using poi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.oncor.ams.core.managers.excel; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.Map; | |
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; | |
import com.beust.jcommander.internal.Lists; | |
/** | |
* Refer this link: https://howtodoinjava.com/java/library/readingwriting-excel-files-in-java-poi-tutorial/ | |
* | |
*/ | |
public class ExcelManager { | |
public Map<String, String> getExcelRowData(String fileName, String sheetName, String rowId) throws IOException { | |
//Define the column names here or pass it as a parameter to make this method resuable | |
List<String> clmNamesList = Lists.newArrayList("TD_ID","CC_URL","CC_UserID","CC_Pwd","MeterNum","MeterType","MeterModel","Command"); | |
// List<String> returnList = new ArrayList<>(); | |
Map<String, String> returnMap = new HashMap<>(); | |
FileInputStream file = new FileInputStream(new File(fileName)); | |
XSSFWorkbook workbook = new XSSFWorkbook(file); | |
XSSFSheet sheet = workbook.getSheet(sheetName); | |
//Iterate through each rows one by one | |
Iterator<Row> rowIterator = sheet.iterator(); | |
//Get the row id which mathces the row id passed in the method and then get the data from the row and save in the list | |
while (rowIterator.hasNext()) { | |
Row row = rowIterator.next(); | |
if (row.getCell(0).getStringCellValue().equalsIgnoreCase(rowId)){ | |
Iterator<Cell> cellIterator = row.cellIterator(); | |
while (cellIterator.hasNext()) { | |
Cell cell = cellIterator.next(); | |
returnMap.put(clmNamesList.get(cell.getColumnIndex()), cell.getStringCellValue()); | |
// returnList.add(cell.getStringCellValue()); | |
} | |
break; | |
} | |
} | |
workbook.close(); | |
file.close(); | |
return returnMap; | |
} | |
} | |
/* | |
<dependency> | |
<groupId>org.apache.poi</groupId> | |
<artifactId>poi</artifactId> | |
<version>5.2.2</version> | |
</dependency> | |
<dependency> | |
<groupId>org.apache.poi</groupId> | |
<artifactId>poi-ooxml</artifactId> | |
<version>5.2.2</version> | |
</dependency> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment