Skip to content

Instantly share code, notes, and snippets.

Created April 26, 2014 02:15
Show Gist options
  • Save anonymous/11310012 to your computer and use it in GitHub Desktop.
Save anonymous/11310012 to your computer and use it in GitHub Desktop.
Load Excel Data to Java Class
package test;
import java.util.ArrayList;
import java.util.List;
public class DummyData {
List<List<Integer>> _data = new ArrayList<List<Integer>>();
public void addRow (List<Integer> row) {
_data.add(row);
}
public List<List<Integer>> getData () {
return _data;
}
public List<Integer> getRowSum () {
List<Integer> rowSum = new ArrayList<Integer>();
for (List<Integer> row : _data) {
Integer sum = 0;
for (Integer i : row) {
sum += i;
}
rowSum.add(sum);
}
return rowSum;
}
}
package test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestExcelCalc {
private static String CHAR_SET = "UTF-16LE";
public static void main (String args[])
throws Exception {
// convert excel file to InputStream
InputStream is = excelToInputStream("test.xlsx");
// load InputStream to DummyData class
DummyData dd = inputStreamToDummyData(is);
// output some calculation result
for (Integer i : dd.getRowSum()) {
System.out.println(i);
}
}
// convert excel file to InputStream
private static InputStream excelToInputStream (String filePath)
throws InvalidFormatException, IOException {
// create workbook from file
// and get first sheet
Sheet sheet = new XSSFWorkbook(OPCPackage.open(new File(filePath)))
.getSheetAt(0);
StringBuilder sb = new StringBuilder("");
// load all data into StringBuilder
for (Row r : sheet) {
for (Cell c : r) {
if (sb.length() > 0)
sb.append(" ");
sb.append(new Double(c.getNumericCellValue()).intValue());
}
}
// convert result String to InputStream
return new ByteArrayInputStream(sb.toString().getBytes(CHAR_SET));
}
// load InputStream to DummyData class
private static DummyData inputStreamToDummyData (InputStream is) {
// create DummyData and Scanner
DummyData dd = new DummyData();
Scanner sc = new Scanner(is, CHAR_SET);
// put data into DummyData class
List<Integer> row = new ArrayList<Integer>();
while (sc.hasNext()) {
row.add(sc.nextInt());
if (row.size() == 3) {
dd.addRow(row);
row = new ArrayList<Integer>();
}
}
return dd;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment