Read or Fetch all the column headers in a excel sheet - java

I wanted to just read all the column headers of my excel sheet.
public class Reader_2 {
public static final String SAMPLE_XLSX_FILE_PATH = "C:/Users/kqxk171/Documents/Records Management
Application/9.2_initial_test_report.xlsx";
public static void main(String[] args) throws IOException {
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
System.out.println("=> " + sheet.getSheetName());
}
Sheet sheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
for (Row row: sheet) {
for(Cell cell: row)
{
row.getRowNum();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
System.out.println();
}
}
}

Related

Apache POI org.apache.poi.xssf.streaming.SXSSFWorkbook generating excel report with missing header names

I am using apache poi library to dynamically generate excel report. Previously I used HSSFWorkbook class to create excel sheet.when I generated an excel report with a large number of records I got out of memory error issue due to Garbage collection overload.due to this reason I switched org.apache.poi.xssf.streaming.SXSSFWorkbook and which resolved the previous outofmemory issue.
Here is my code for generating excel report.
public Workbook getReport(String yearLevels, List<User> userList, Map<Long, Date> map) {
Workbook wb = new SXSSFWorkbook (100);
try {
CellStyle cellStyle1;
CellStyle cellStyle2;
Sheet sheet;
HSSFRichTextString cellValue;
Row row;
Cell cell;
Font font1;
Font font2;
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
sheet = wb.createSheet("User Details Report");
sheet.setColumnWidth(0, 7000);
sheet.setColumnWidth(1, 4000);
sheet.setColumnWidth(2, 4000);
sheet.setColumnWidth(3, 4000);
sheet.setColumnWidth(4, 3000);
sheet.setColumnWidth(5, 9000);
font1 = wb.createFont();
font1.setFontHeightInPoints((short) 10);
font1.setFontName("Arial");
font1.setBold(true);
font2 = wb.createFont();
font2.setFontHeightInPoints((short) 10);
font2.setFontName("Arial");
cellStyle1 = wb.createCellStyle();
cellStyle1.setFont(font1);
cellStyle2 = wb.createCellStyle();
cellStyle2.setFont(font2);
int rowNumber = 0;
CellStyle cellStyle3 = wb.createCellStyle();
cellStyle3.setFont(font1);
cellStyle3.setAlignment(HorizontalAlignment.CENTER);
row = sheet.createRow(rowNumber);
int cellValueCount=0;
Cell userName = row.getCell(cellValueCount, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
userName.setCellValue("Username");
userName.setCellStyle(cellStyle3);
Cell firstName = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
firstName.setCellValue("First Name");
firstName.setCellStyle(cellStyle3);
Cell lastName = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
lastName.setCellValue("Last Name");
lastName.setCellStyle(cellStyle3);
Cell yearLevel = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
yearLevel.setCellValue("Year Level");
yearLevel.setCellStyle(cellStyle3);
Cell paidStatus = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
paidStatus.setCellValue("Student No");
paidStatus.setCellStyle(cellStyle3);
Cell dateTitleFulfilled = row.getCell(cellValueCount++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
dateTitleFulfilled.setCellValue("Date Fulfilled");
dateTitleFulfilled.setCellStyle(cellStyle3);
CellStyle cellStyle4 = wb.createCellStyle();
cellStyle4.setFont(font2);
cellStyle4.setAlignment(HorizontalAlignment.CENTER);
int columnNumber = 0;
for (User user : userList) {
columnNumber = 0;
rowNumber++;
row = sheet.createRow(rowNumber);
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getPrincipalId());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getFirstName());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getLastName());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
/*cell = row.getCell(columnNumber, Row.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getStudentNumber());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;*/
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(Integer.toString(user.getYearLevel()));
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cellValue = new HSSFRichTextString(user.getJppFulfillmentTags());
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
columnNumber++;
cell = row.getCell(columnNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
Date date = map.get(user.getId());
if (date != null) {
String eventDate = df1.format(date);
cellValue = new HSSFRichTextString(eventDate);
} else {
cellValue = new HSSFRichTextString("");
}
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle4);
}
} catch (Exception e) {
logger.error("ReportService::getReport Error Report Creation ", e);
}
return wb;
}
ReportService reportService = new ReportService();
Workbook wb = reportService.getReport(yearLevelsString, userList, map);
OutputStream out = response.getOutputStream();
if (request.getParameter("exportAs") == null || !request.getParameter("exportAs").equalsIgnoreCase("xls")) {
response.setHeader("Content-Disposition", "attachment;filename=User_Report.csv");
CSVPrinter csvPrinter = reportService.writeWorkbookAsCSVToOutputStream(wb, out);
csvPrinter.flush();
csvPrinter.close();
} else {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=User_Report.xls");
wb.write(out);
out.close();
}
public CSVPrinter writeWorkbookAsCSVToOutputStream(Workbook workbook, OutputStream out) throws IOException {
CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(out), CSVFormat.DEFAULT);
try {
if (workbook != null) {
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
csvPrinter.print(cell.getStringCellValue());
}
csvPrinter.println();
}
}
} catch (Exception e) {
logger.error("ReportService::writeWorkbookAsCSVToOutputStream Error Report Creation ", e);
}
return csvPrinter;
}
After this implementation when I download excel report with more than 100 records I am getting report without header names.
but when I download excel report with less than 100 records I am getting report with cell header name without issue.
Why I the excel report is generating without header names when excel report having more than 100 records?

Java Read Excel File via FileDialog

I get an IOException with the code below. Whats the problem?
What I want is to Read an Excel File xlsm and xls or xlsx via the filedialog after the import read the excel and work with it.
public class start {
public static void main(String[] args) throws IOException, InvalidFormatException {
JFrame yourJFrame = new JFrame();
FileDialog fd = new FileDialog(yourJFrame, "Choose a file", FileDialog.LOAD);
fd.setVisible(true);
String filename = fd.getFile();
String filepth = fd.getDirectory();
Workbook workbook = WorkbookFactory.create(new File(filepth + filename));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
System.out.println("=> " + sheet.getSheetName());
}
String
DataFormatter dataFormatter = new DataFormatter();
System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
System.out.println();
}
workbook.close();
}
}

How can I define Buttons and TextViews in static main or after that?

Here is my activity. I am stuck in activity and need help please.
I need to read data, have them as key and result in a map<>. get keys from user by press button show the result of the key and then another button to add them to the list if user approve it.
public class ExcelReaderActivity extends AppCompatActivity {
public static final String SAMPLE_XLSX_FILE_PATH = "/home/saeid/Documents/ABBREV.xlsx";
public static final Map<String, String> numberDescMap = new HashMap<>();
public final TextView productInput = findViewById(R.id.textView_InputProductNumber);
public final TextView productName = findViewById(R.id.textView_ProductName);
public final Button checkInput = findViewById(R.id.button_GO);
public final Button addInput = findViewById(R.id.button_AddProduct);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reader_excel);
}
public static void main(String[] args) throws IOException, InvalidFormatException {
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
// Retrieving the number of sheets in the Workbook
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
// obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
System.out.println("=> " + sheet.getSheetName());
}
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
Row rowCount = sheet.getRow(0);
int totalNumberOfRows = sheet.getPhysicalNumberOfRows();
int totalNumberOfColumns = rowCount.getPhysicalNumberOfCells();
System.out.print("number of rows => " + totalNumberOfRows + "\n");
System.out.print("number of columns => " + totalNumberOfColumns + "\n");
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// obtain a rowIterator and columnIterator and iterate over them
System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
Iterator<Row> rowIterator = sheet.rowIterator();
for (int currentRow = 1; currentRow < totalNumberOfRows; currentRow++){
Row row = rowIterator.next();
row = sheet.getRow(currentRow);
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
String cellValue0 = dataFormatter.formatCellValue(cell0);
String cellValue1 = dataFormatter.formatCellValue(cell1);
numberDescMap.put(cellValue0,cellValue1);
//System.out.print(currentRow + "- *" + dbNumbers + "*" + "*" + description + "*" + "\n");
}
List<String> dbNumbers = new ArrayList(numberDescMap.keySet());
List<String> description = new ArrayList(numberDescMap.values());
int checkIndex = 1;
for (String mapkeys : dbNumbers){
System.out.println(checkIndex++ + "- " + mapkeys + "==>" +numberDescMap.get(mapkeys) + "\n");
}
// Closing the workbook
workbook.close();
}
}
I need to access Buttons and TextViews after main(). I tried several ways but not succeeded so far.
I need to work with Buttons and TextViews after the result in main. I need the map<> before using them.
I tried make them static as well or define in onCreate() but was not successful. I appreciate any help.
I did this edit after the answer I got
this is the Java file for act as a method
public class FileReader{
private final Activity activity;
public FileReader(Activity activity) {this.activity = activity;
}
public static final String SAMPLE_XLSX_FILE_PATH = "/home/saeid/Documents/ABBREV.xlsx";
public static final Map<String, String> numberDescMap = new HashMap<>();
public Map<String, String> ExcelFileReader() {
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = null;
try {
workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
}
// obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
//System.out.println("=> " + sheet.getSheetName());
}
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
Row rowCount = sheet.getRow(0);
int totalNumberOfRows = sheet.getPhysicalNumberOfRows();
int totalNumberOfColumns = rowCount.getPhysicalNumberOfCells();
System.out.println("number of rows => " + totalNumberOfRows );
System.out.println("number of columns => " + totalNumberOfColumns );
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// 1. You can obtain a rowIterator and columnIterator and iterate over them
System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
Iterator<Row> rowIterator = sheet.rowIterator();
for (int currentRow = 1; currentRow < totalNumberOfRows; currentRow++) {
Row row = rowIterator.next();
row = sheet.getRow(currentRow);
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
String cellValue0 = dataFormatter.formatCellValue(cell0);
String cellValue1 = dataFormatter.formatCellValue(cell1);
numberDescMap.put(cellValue0, cellValue1);
//System.out.print(currentRow + "- *" + dbNumbers + "*" + "*" + description + "*" + "\n");
}
// Closing the workbook
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
return numberDescMap;
}
}
I did a debug , the workbook is always null and I get null in activity.
and this is how I call it in activity
FileReader fileReader = new FileReader(this);
final Map<String, String> numberDescMap = fileReader.ExcelFileReader();
Make sure you understand the activity lifecycle properly. Checkout this link
You don't need to use public static void main
public class ExcelReaderActivity extends AppCompatActivity {
public static final String SAMPLE_XLSX_FILE_PATH = "/home/saeid/Documents/ABBREV.xlsx";
public static final Map<String, String> numberDescMap = new HashMap<>();
public final TextView productInput ;
public final TextView productName;
public final Button checkInput ;
public final Button addInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reader_excel);
productInput = findViewById(R.id.textView_InputProductNumber);
productName = findViewById(R.id.textView_ProductName);
checkInput = findViewById(R.id.button_GO);
addInput = findViewById(R.id.button_AddProduct);
createWorkbook();
}
createWorkbook(){
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
// Retrieving the number of sheets in the Workbook
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
// obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
System.out.println("=> " + sheet.getSheetName());
}
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
Row rowCount = sheet.getRow(0);
int totalNumberOfRows = sheet.getPhysicalNumberOfRows();
int totalNumberOfColumns = rowCount.getPhysicalNumberOfCells();
System.out.print("number of rows => " + totalNumberOfRows + "\n");
System.out.print("number of columns => " + totalNumberOfColumns + "\n");
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// obtain a rowIterator and columnIterator and iterate over them
System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
Iterator<Row> rowIterator = sheet.rowIterator();
for (int currentRow = 1; currentRow < totalNumberOfRows; currentRow++){
Row row = rowIterator.next();
row = sheet.getRow(currentRow);
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
String cellValue0 = dataFormatter.formatCellValue(cell0);
String cellValue1 = dataFormatter.formatCellValue(cell1);
numberDescMap.put(cellValue0,cellValue1);
//System.out.print(currentRow + "- *" + dbNumbers + "*" + "*" + description + "*" + "\n");
}
List<String> dbNumbers = new ArrayList(numberDescMap.keySet());
List<String> description = new ArrayList(numberDescMap.values());
int checkIndex = 1;
for (String mapkeys : dbNumbers){
System.out.println(checkIndex++ + "- " + mapkeys + "==>" +numberDescMap.get(mapkeys) + "\n");
}
// Closing the workbook
workbook.close();
}
}
You can use all the views instance inside createWorkbook method
Do like this
public class ExcelReaderActivity extends AppCompatActivity {
public static final String SAMPLE_XLSX_FILE_PATH = "/home/saeid/Documents/ABBREV.xlsx";
public static final Map<String, String> numberDescMap = new HashMap<>();
private TextView productInput, productName ;
private Button checkInput , addInput ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reader_excel);
productName = findViewById(R.id.textView_ProductName);
productInput = findViewById(R.id.textView_InputProductNumber);
checkInput = findViewById(R.id.button_GO);
addInput = findViewById(R.id.button_AddProduct);
workBookCalculation();
}
public void workBookCalculation() throws IOException, InvalidFormatException {
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
// Retrieving the number of sheets in the Workbook
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
// obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
System.out.println("=> " + sheet.getSheetName());
}
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
Row rowCount = sheet.getRow(0);
int totalNumberOfRows = sheet.getPhysicalNumberOfRows();
int totalNumberOfColumns = rowCount.getPhysicalNumberOfCells();
System.out.print("number of rows => " + totalNumberOfRows + "\n");
System.out.print("number of columns => " + totalNumberOfColumns + "\n");
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// obtain a rowIterator and columnIterator and iterate over them
System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
Iterator<Row> rowIterator = sheet.rowIterator();
for (int currentRow = 1; currentRow < totalNumberOfRows; currentRow++){
Row row = rowIterator.next();
row = sheet.getRow(currentRow);
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
String cellValue0 = dataFormatter.formatCellValue(cell0);
String cellValue1 = dataFormatter.formatCellValue(cell1);
numberDescMap.put(cellValue0,cellValue1);
//System.out.print(currentRow + "- *" + dbNumbers + "*" + "*" + description + "*" + "\n");
}
List<String> dbNumbers = new ArrayList(numberDescMap.keySet());
List<String> description = new ArrayList(numberDescMap.values());
int checkIndex = 1;
for (String mapkeys : dbNumbers){
System.out.println(checkIndex++ + "- " + mapkeys + "==>" +numberDescMap.get(mapkeys) + "\n");
}
// Closing the workbook
workbook.close();
}
}
And use textview any where in the activity;

how to read the merged formula VLOOKUP cell value using poi

i have an excel file with merged and formula cell which is using the VLOOKUP(B16,Data!$A$2:$C$7,3,0). In specific cell $40 is appearing as value. but when i try to read the value it is reading only 40 and skipping the $ part.
public static void main(String[] args) {
try {
String excelFilePath = "D:\\test\\1_sample1_UA Logo Order form update on 2016-12-06.xls";
InputStream input = new BufferedInputStream(new FileInputStream(
excelFilePath));
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
workbook.setForceFormulaRecalculation(true);
Sheet sheet = workbook.getSheetAt(3);
Row row = sheet.getRow(15);
Cell cell = row.getCell(7);
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress region = sheet.getMergedRegion(i); // Region of
// merged
// cells
int colIndex = region.getFirstColumn();
int rowNum = region.getFirstRow();
if (region.isInRange(15, 7)) {
CellReference cellReference = new CellReference("H15");
Row row2 = sheet.getRow(cellReference.getRow());
Cell cell2 = row2.getCell(cellReference.getCol());
// formulla evaluato
FormulaEvaluator forEvaluator = workbook
.getCreationHelper().createFormulaEvaluator();
workbook.getCreationHelper().createFormulaEvaluator()
.evaluateAll();
workbook.setForceFormulaRecalculation(true);
CellValue cellValue = forEvaluator.evaluate(cell2);
System.out.println("cell string value2 :: "
+ cellValue.formatAsString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

Covert XLSX row into string and add to array

I am trying to get a basic java program to read from a xlsx file and put each row into an arrayList as a string, where later on I will then split that String up of that row.
Below is my code, however i'm trying to figure out where I have gone wrong as it doesn't appear to be doing anything.
List<String> text = new ArrayList<String>();
Workbook wb = WorkbookFactory.create(new File("input.xlsx"));
DataFormatter fmt = new DataFormatter();
Sheet s = wb.getSheetAt(0);
for (Row r : s) {
StringBuffer sb = new StringBuffer();
for (Cell c : r) {
if (sb.length() > 0) sb.append(" - ");
sb.append(fmt.formatCell(c));
}
text.append(sb.toString());
}
Any help would be appreciated.
You are not reading any cell. See this example:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
//..
FileInputStream file = new FileInputStream(new File("C:\\test.xlsx"));
//Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook (file);
//Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Categories