Failure Sharing

Bootup your energy with sharing failure.

Javaで、Excelのシートをインポートする。

必要なライブラリ

poi-3.16.jar
mvnrepository.comからダウンロードできる。

File

f:id:woosyume:20180916170252p:plain

Code

Util class

package demo.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

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;

public class Excel {
    public static String[][] get(String filename) {
        String[][] dataTable = null;
        File file = new File(filename);
        
        try {
            // Create a file input stream to read Excel workbook and worksheet
            FileInputStream fis = new FileInputStream(file);
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fis);
            HSSFSheet xlsSheet = hssfWorkbook.getSheetAt(0); // does not support auto close.
            
            // Get the number of rows and columns
            int numRows = xlsSheet.getLastRowNum() + 1;
            int numCols = xlsSheet.getRow(0).getLastCellNum();
            
            // Create double array data table - rows x cols
            // We will return this data table
            dataTable = new String[numRows][numCols];
            
            // For each row, create a HSSFRow, then iterate through the 'columns'
            // For each column, create an HSSFCell to grab the value at the specified cell(ii, j)
            for (int i = 0; i < numRows; i++) {
                HSSFRow xlsRow = xlsSheet.getRow(i);
                for (int j = 0; j < numCols; j++) {
                    HSSFCell xlsCell = xlsRow.getCell(j);
                    dataTable[i][j] = xlsCell.toString();
                }
            }
                    
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataTable;
    }
}

Executor

 public static void readExcel() {
        String filename = "/Users/woohyeok.kim/Downloads/UserLogin.xls";
        String[][] data = Excel.get(filename);
        for (String[] record : data) {
            System.out.println("\nNEW RECORD");
            System.out.println(record[0]);
            System.out.println(record[1]);
            System.out.println(record[2]);
        }
    }

Console

NEW RECORD
Ellie Prynne
ep@testemail.com
ep1password

NEW RECORD
Shawn Thompson
sw@testemail.com
sw2password

NEW RECORD
Michael Lane
ml@testemail.com
ml3password

NEW RECORD
Janelle Von
jv@testemail.com
jv4password

Commit

github.com