Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package miscellaneous;
- import org.apache.poi.hssf.usermodel.HSSFCell;
- import org.apache.poi.hssf.usermodel.HSSFRow;
- import org.apache.poi.hssf.usermodel.HSSFSheet;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.junit.Test;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Iterator;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import static org.junit.Assert.assertTrue;
- /**
- * Created by Sandeep on 8/6/15.
- */
- public class ProcessExcelFile {
- /**
- * Open an excel file, iterate the rows of a worksheet and calculate the total of numeric values of each row.
- *
- * @return the Map to return
- */
- public Map ReadExcelFile() {
- InputStream fileInputStream = null;
- HSSFWorkbook hssfWorkbook;
- HSSFSheet sheet;
- HSSFRow row;
- HSSFCell cell;
- Iterator rowIterator, cellIterator;
- String employeeName = null;
- double total = 0;
- Map<String, Double> empMonthlyProdStat = new LinkedHashMap<String, Double>();
- try {
- fileInputStream = new FileInputStream("/home/sandeep/Desktop/MyDocs/repos/git-repos/public/MAVEN-BASE/src/test/resources/TestExcel.xls");
- hssfWorkbook = new HSSFWorkbook(fileInputStream);
- sheet = hssfWorkbook.getSheetAt(0);
- rowIterator = sheet.rowIterator();
- while (rowIterator.hasNext()) {
- row = (HSSFRow) rowIterator.next();
- cellIterator = row.cellIterator();
- while (cellIterator.hasNext()) {
- cell = (HSSFCell) cellIterator.next();
- if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
- employeeName = cell.getStringCellValue();
- } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
- total = total + cell.getNumericCellValue();
- } else {
- //System.out.println("");// Handle other types
- }
- }
- empMonthlyProdStat.put(employeeName, total);
- total = 0;
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return empMonthlyProdStat;
- }
- @Test
- public void testReadExcelFile() throws Exception {
- assertTrue("This will succeed....", ReadExcelFile().size()==3);
- }
- }
Add Comment
Please, Sign In to add comment