Groovy and POI: Can I read/write at the same time? - groovy

I'm new to groovy, and I've used the ExcelBuilder code referenced below to iterate through an excel spreadsheet to grab data. Is there an easy to write data as I iterate?
For example, row 1 might have data like this (CSV):
value1,value2
And after I iterate, I want it to look like this:
value1,value2,value3
http://www.technipelago.se/content/technipelago/blog/44

Yes, this can be done! As I got into the guts of it, I realized that the problem I was trying to solve wasn't the same as trying to read and write from the same file at the same time, but rather the excel data was stored in an object that I could freely manipulate whenever I wanted. So I added methods specific to my needs - which may or many not meet the needs of anyone else - and I post them here for smarter people to pick apart. At the end of it all, it is now doing what I want it to do.
I added a cell method that takes an index (number or label) and a value which will update a cell for the current row in context (specifically while using .eachLine()), and a .putRow() method that adds a whole row to the spreadsheet specified. It also handles Excel 2003, 2007, and 2010 formats. When files, sheets, or cells referenced don't exist, they get created. Since my source spreadsheets often have formulas and charts ready to display the data I'm entering, the .save() and .saveAs() methods call .evaluateAllFormulaCells() before saving.
To see the code I started with and examples of how it works, check out this blog entry
Note that both the .save() and .saveAs() methods reload the workbook from the saved file immediately after saving. This is a workaround to a bug in Apache POI that doesn't seem to be fixed yet (see Exception when writing to the xlsx document several times using apache poi).
import groovy.lang.Closure;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
class Excel
{
def workbook;
def sheet;
def labels;
def row;
def infilename;
def outfilename;
Excel(String fileName)
{
HSSFRow.metaClass.getAt = {int index ->
def cell = delegate.getCell(index);
if(! cell)
{
return null;
}
def value;
switch (cell.cellType)
{
case HSSFCell.CELL_TYPE_NUMERIC:
if(HSSFDateUtil.isCellDateFormatted(cell))
{
value = cell.dateCellValue;
}
else
{
value = new DataFormatter().formatCellValue(cell);
}
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = cell.booleanCellValue
break;
default:
value = new DataFormatter().formatCellValue(cell);
break;
}
return value
}
XSSFRow.metaClass.getAt = {int index ->
def cell = delegate.getCell(index);
if(! cell)
{
return null;
}
def value = new DataFormatter().formatCellValue(cell);
switch (cell.cellType)
{
case XSSFCell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell))
{
value = cell.dateCellValue;
}
else
{
value = new DataFormatter().formatCellValue(cell);
}
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
value = cell.booleanCellValue
break;
default:
value = new DataFormatter().formatCellValue(cell);
break;
}
return value;
}
infilename = fileName;
outfilename = fileName;
try
{
workbook = WorkbookFactory.create(new FileInputStream(infilename));
}
catch (FileNotFoundException e)
{
workbook = (infilename =~ /(?is:\.xlsx)$/) ? new XSSFWorkbook() : new HSSFWorkbook();
}
catch (Exception e)
{
e.printStackTrace();
}
}
def getSheet(index)
{
def requested_sheet;
if(!index) index = 0;
if(index instanceof Number)
{
requested_sheet = (workbook.getNumberOfSheets >= index) ? workbook.getSheetAt(index) : workbook.createSheet();
}
else if (index ==~ /^\d+$/)
{
requested_sheet = (workbook.getNumberOfSheets >= Integer.valueOf(index)) ? workbook.getSheetAt(Integer.valueOf(index)) : workbook.createSheet();
}
else
{
requested_sheet = (workbook.getSheetIndex(index) > -1) ? workbook.getSheet(index) : workbook.createSheet(index);
}
return requested_sheet;
}
def cell(index)
{
if (labels && (index instanceof String))
{
index = labels.indexOf(index.toLowerCase());
}
if (row[index] == null)
{
row.createCell(index);
}
return row[index];
}
def cell(index, value)
{
if (labels.indexOf(index.toLowerCase()) == -1)
{
labels.push(index.toLowerCase());
def frow = sheet.getRow(0);
def ncell = frow.createCell(labels.indexOf(index.toLowerCase()));
ncell.setCellValue(index.toString());
}
def cell = (labels && (index instanceof String)) ? row.getCell(labels.indexOf(index.toLowerCase())) : row.getCell(index);
if (cell == null)
{
cell = (index instanceof String) ? row.createCell(labels.indexOf(index.toLowerCase())) : row.createCell(index);
}
cell.setCellValue(value);
}
def putRow (sheetName, Map values = [:])
{
def requested_sheet = getSheet(sheetName);
if (requested_sheet)
{
def lrow;
if (requested_sheet.getPhysicalNumberOfRows() == 0)
{
lrow = requested_sheet.createRow(0);
def lcounter = 0;
values.each {entry->
def lcell = lrow.createCell(lcounter);
lcell.setCellValue(entry.key);
lcounter++;
}
}
else
{
lrow = requested_sheet.getRow(0);
}
def sheetLabels = lrow.collect{it.toString().toLowerCase()}
def vrow = requested_sheet.createRow(requested_sheet.getLastRowNum() + 1);
values.each {entry->
def vcell = vrow.createCell(sheetLabels.indexOf(entry.key.toLowerCase()));
vcell.setCellValue(entry.value);
}
}
}
def propertyMissing(String name)
{
cell(name);
}
def propertyMissing(String name, value)
{
cell(name, value);
}
def eachLine (Map params = [:], Closure closure)
{
/*
* Parameters:
* skiprows : The number of rows to skip before the first line of data and/or labels
* offset : The number of rows to skip (after labels) before returning rows
* max : The maximum number of rows to iterate
* sheet : The name (string) or index (integer) of the worksheet to use
* labels : A boolean to treat the first row as a header row (data can be reference by label)
*
*/
def skiprows = params.skiprows ?: 0;
def offset = params.offset ?: 0;
def max = params.max ?: 9999999;
sheet = getSheet(params.sheet);
def rowIterator = sheet.rowIterator();
def linesRead = 0;
skiprows.times{ rowIterator.next() }
if(params.labels)
{
labels = rowIterator.next().collect{it.toString().toLowerCase()}
}
offset.times{ rowIterator.next() }
closure.setDelegate(this);
while(rowIterator.hasNext() && linesRead++ < max)
{
row = rowIterator.next();
closure.call(row);
}
}
def save ()
{
if (workbook.getClass().toString().indexOf("XSSF") > -1)
{
XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) workbook);
}
else
{
HSSFFormulaEvaluator.evaluateAllFormulaCells((HSSFWorkbook) workbook);
}
if (outfilename != null)
{
try
{
FileOutputStream output = new FileOutputStream(outfilename);
workbook.write(output);
output.close();
workbook = null;
workbook = WorkbookFactory.create(new FileInputStream(outfilename));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
def saveAs (String fileName)
{
if (workbook.getClass().toString().indexOf("XSSF") > -1)
{
XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) workbook);
}
else
{
HSSFFormulaEvaluator.evaluateAllFormulaCells((HSSFWorkbook) workbook);
}
try
{
FileOutputStream output = new FileOutputStream(fileName);
workbook.write(output);
output.close();
outfilename = fileName;
workbook = null;
workbook = WorkbookFactory.create(new FileInputStream(outfilename));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
If you see any glaring errors or ways to improve (other than style), I'd love to hear them. Again, Groovy is not a language I have much experience with, and I haven't done anything with Java in several years, so I'm sure there might be some better ways to do things.

Related

Groovy include new Groovy script

I'm pretty new to Groovy an I want to import a class from another groovy script in the main groovy script. I saw already this post. However due to environment restrictions I can't us functions like GroovyClassLoader or or import any libs/frameworks. The only possibility I have is to use the evaluate method.
I tried this:
main script (The evaluate does not throw any error)
File csvFile = new File("./Csvreader.groovy");
evaluate(csvFile);
Csvreader script
class CSVReader{
def csvFile = new File('./test.csv');
def separatorChar = ";"
def values = [];
def headers = [];
void setSeperator(String s){
if(s != ""){
separatorChar = s;
}
}
void readCsv(){
csvFile.eachLine{ line, number ->
if(number == 1){
def head = line.split(separatorChar);
for (entry in head) {
headers.add(entry);
}
} else{
def value = line.split(separatorChar);
def map =[:];
def i = 0;
for (entry in value) {
map.put(headers[i], entry);
i++;
}
values.add(map);
}
}
}
def getValues(){
return values;
}
def getHeaders(){
return headers;
}
def getSize(){
return values.size();
}
def getLine(def keyParam, def value){
for(int i = 0; i < values.size(); i++){
def line = values[i];
if(values[i][keyParam] == value){
return values[i];
}
}
}
}
However I would need to pass parameters with the evaluate call (and I would move the methods outside the class) or I need to create an instance of the class.
Unfortunately I don't really know how I can do that, does anyone have a solution for that?
you could try to put at the end of your Csvreader.groovy file the expression return CSVReader.class that will return you a compiled class.
Then in your caller script you could create an instance of this class and use it as any other class instance.
Csvreader.groovy
class CSVReader{
def separatorChar = ";"
void setSeparator(String s){
if(s != ""){
separatorChar = s;
}
}
}
return CSVReader.class
caller script
File csvFile = new File("./Csvreader.groovy")
def CSVReaderClass = evaluate(csvFile)
def cvsReader = CSVReaderClass.newInstance()
cvsReader.setSeparator("Z")
println cvsReader.separatorChar

Nexus3 only downloads 50 in list

So I have a code that downloads the version nr of each nuget package but it all stops after 50 in list.
I use jenkins with groovy code and get out a list of versions.
import groovy.json.JsonSlurperClassic
import groovy.json.JsonBuilder
import wslite.rest.*
def data = new URL("http://nexus.xx.xx.se:8081/service/rest/v1/search?repository=xx-sx-nuget&name=XXXFrontend").getText()
println data
/**
* 'jsonString' is the input json you have shown
* parse it and store it in collection
*/
Map convertedJSONMap = new JsonSlurperClassic().parseText(data)
//If you have the nodes then fetch the first one only
if(convertedJSONMap."items"){
println "Version : " + convertedJSONMap."items"[0]."version"
}
def list = convertedJSONMap.items.version
Collections.sort(list)
list
So the problem is that it only get 50 of the versions. How can I get more than 50? I have read about a continuetoken but I dont understand how to use that?
UPDATE
I have added this but still dont work
while(convertedJSONMap."continuesToken" != null){
def token = convertedJSONMap."continuationToken"
def data2 = new URL("http://nexus.xxx.xxx.se:8081/service/rest/v1/search?repository=xxx-xx-nuget&name=xxxxxx&continuationToken=" +token).getText()
convertedJSONMap = JsonSlurperClassic().parseText(data2)
}
This is how I solved it for me. It is just a snippet of the code that I use
def json = sendRequest(url)
addResultToMap(map2, json, release) //I do something here with the received result
def continuationToken = json.continuationToken
if (continuationToken != null) {
while (continuationToken != null) {
json = sendRequest(url + "&continuationToken=" + continuationToken)
addResultToMap(map2, json, release) //I do something here with the received result as above
continuationToken = json.continuationToken
}
}
And my sendRequest method looks like this
def sendRequest(def url, String method = "GET") {
String userPass = "${nexus.username}:${nexus.password}"
String basicAuth = "Basic " + "${printBase64Binary(userPass.getBytes())}"
def connection = new URL( url ).openConnection() as HttpURLConnection
connection.setRequestProperty('Accept', 'application/json' )
connection.setRequestProperty('Authorization', basicAuth)
connection.setRequestMethod(method)
try {
if ( connection.responseCode <= 299 ) {
if (connection.responseCode == 200) {
return connection.inputStream.withCloseable { inStream -> new JsonSlurper().parse( inStream as InputStream ) }
}
} else {
displayAndLogError(connection.responseCode + ": " + connection.inputStream.text, loglevel.DEBUG)
}
} catch(Exception exc) {
displayAndLogError(exc.getMessage())
}
}
Here is an alternative :
import groovy.json.JsonSlurper
try {
N_PAGES_MAX = 10
List<String> versions = new ArrayList<String>()
continuationToken = "123"
artifactsUrl = "http://nexus.zzz.local/service/rest/v1/components?repository=releases-super-project"
currentPage = 1
while (true) {
artifactsObjectRaw = ["curl", "-s", "-H", "accept: application/json", "-k", "--url", "${artifactsUrl}"].execute().text
artifactsJsonObject = (new JsonSlurper()).parseText(artifactsObjectRaw)
continuationToken = artifactsJsonObject.continuationToken
if (continuationToken!=null && continuationToken!='123') {
artifactsUrl = artifactsUrl + "&continuationToken=$continuationToken"
}
def items = artifactsJsonObject.items
for(item in items){
versions.add(item.name)
}
currentPage += 1
if (continuationToken==null || currentPage>N_PAGES_MAX) break
}
return versions.sort().reverse()
}
catch (Exception e) {
print "There was a problem fetching the versions"
}

Selenium -Extracting data from excel and writing to web page -Issues in program

I am trying to extract data from excel and write it to a web page . As I click on a drop down"I am " provided in the link in the code below the remaining contents of the page changes .I have made certain cells as blank.I wrote the code but getting some exceptions .Please help
import java.io.*;
import java.util.concurrent.TimeUnit;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Copyprogram {
public static WebDriver driver=new FirefoxDriver();
public static void main(String[] args)
{
driver.get("http://www.deal4loans.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("html/body/div[4]/div/div/div[1]/a[1]")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try {
FileInputStream fis = new FileInputStream("C:\\Users\\user\\Documents\\Copy of Booklet1.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet("testdata");
// Loop through all rows in the sheet
// Start at row 1 as row 0 is our header row
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
for(int i = 1;i<=rowCount;i++)
{
Row row1 = sheet.getRow(i);
try {
Thread.sleep(2000);
} catch (Exception e)
{
// TODO: handle exception
}
runTest(row1.getCell(1).toString(),row1.getCell(2).toString(),row1.getCell(3).toString(),row1.getCell(4).toString(),row1.getCell(5).toString(),row1.getCell(6).toString(),row1.getCell(7).toString(),row1.getCell(8).toString(),row1.getCell(9).toString(),row1.getCell(10).toString(),row1.getCell(11).toString(),row1.getCell(12).toString(),row1.getCell(13).toString() );
System.out.println(row1.getCell(1).toString());
System.out.println(row1.getCell(2).toString());
System.out.println(row1.getCell(3).toString());
System.out.println(row1.getCell(4).toString());
System.out.println(row1.getCell(5).toString());
System.out.println(row1.getCell(6).toString());
System.out.println(row1.getCell(7).toString());
System.out.println(row1.getCell(8).toString());
System.out.println(row1.getCell(9).toString());
System.out.println(row1.getCell(10).toString());
if (i<rowCount)
{
driver.navigate().back();
}
System.out.println(i);
}
fis.close();
} catch (IOException e) {
System.out.println("Test data file not found");
}
driver.close();
}
public static void runTest(String name,String mailid,String query,String city,String mob,String pdt,String PL,String HL,String CL,String LA,String BL,String CC,String ass)
{
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/input")).sendKeys(name);
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/input")).sendKeys(mailid);
Select listbox1 = new Select(driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[3]/td[2]/select")));
listbox1.selectByValue(query);
String selectedValue =listbox1.getFirstSelectedOption().getText();
Select listbox2 = new Select(driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[4]/td[2]/select")));
listbox2.selectByValue(city);
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[6]/td[2]/input")).sendKeys(mob);
if (selectedValue=="1")
{
Select listbox3 = new Select(driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[7]/td/div[2]/table/tbody/tr/td[2]/select")));
listbox3.selectByValue(pdt);
}
else
{
if (PL == null && PL.length() == 0)
{
driver.findElement(By.cssSelector("input[value=PL]")).click();
System.out.println(PL);
}
if(HL == null && HL.length() == 0)
{
driver.findElement(By.cssSelector("input[value=HL]")).click();
}
if(CL == null && CL.length() == 0)
{
driver.findElement(By.cssSelector("input[value=CL]")).click();
}
if(LA == null && LA.length() == 0)
{
driver.findElement(By.cssSelector("input[value=LA]")).click();
}
if(BL == null && BL.length() == 0)
{
driver.findElement(By.cssSelector("input[value=BL]")).click();
}
if(CC== null && CC.length() == 0)
{
driver.findElement(By.cssSelector("input[value=CC]")).click();
}
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[7]/td/div[3]/table/tbody/tr[2]/td[2]/input")).sendKeys(ass);
}
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[9]/td/input")).click();
}
}

Use Groovy To Search A File And Grab Contents Below A String

I'm trying to use Groovy to open a file to search for a specific substring and then grab a different substring that occurs below the first one.
For example the substring I'm searching for is "Charger is enabled. Checking charge parameters..."
and if it is found I want to get a specific string that occurs after this.
Is the best way to do this read the file into memory and search for the index of the first string?
// With Java
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
def localDirectory = "";
def fileName = "";
def searchKey = "Charger is enabled. Checking charge parameters";
def searchKey2 = "";
def errorMessage = "";
FileReader fr;
BufferedReader br;
try
{
File f1 = new File(localDirectory+"/"+fileName);
fr = new FileReader(f1);
br = new BufferedReader(fr);
def keyFound = false;
// Go through line by line.
def line;
while ((line = br.readLine()) != null)
{
// If first string is found, process the second string.
if(line.contains(searchKey))
{
while ((line = br.readLine()) != null)
{
// Do something with the second string.
if(line.contains(searchKey2))
{
keyFound=true;
break;
}
}
}
if(keyFound)
{
break;
}
}
}
catch (Exception e)
{
errorMessage += "\nUnexpected Exception: " + e.getMessage();
for (trace in e.getStackTrace())
{
errorMessage += "\n\t" + trace;
}
}
finally
{
fr?.close();
br?.close();
}
// With Groovy
def localDirectory = "";
def fileName = "";
def searchKey = "Charger is enabled. Checking charge parameters";
def searchKey2 = "";
def errorMessage = "";
try
{
File f1 = new File(localDirectory+"/"+fileName);
def keyFound = false;
// Go through line by line.
def line;
f1.withReader
{
reader ->
while((line = reader.readLine()) != null)
{
// If first string is found, process the second string.
if(line.contains(searchKey))
{
while((line = reader.readLine()) != null)
{
// Do something with the second string.
if(line.contains(searchKey2))
{
keyFound=true;
break;
}
}
}
if(keyFound)
{
break;
}
}
}
}
catch (Exception e)
{
errorMessage += "\nUnexpected Exception: " + e.getMessage();
for (trace in e.getStackTrace())
{
errorMessage += "\n\t" + trace;
}
}

How to read excel file omitting first two rows

I have an excel file of 111 rows. I need to omit first two rows of the sheet and then read the file using java and POI.
You have to skip first two rows using rownum().Here is the sample code
HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
HSSFSheet sheet = workBook.getSheetAt (0);
Iterator<HSSFRow> rows = sheet.rowIterator ();
while (rows.hasNext ())
{
HSSFRow row = rows.next ();
// display row number in the console.
System.out.println ("Row No.: " + row.getRowNum ());
if(row.getRowNum()==0 || row.getRowNum()==1){
continue; //just skip the rows if row number is 0 or 1
}
}
Here is the complete example
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
public class POIExcelReader
{
/** Creates a new instance of POIExcelReader */
public POIExcelReader ()
{}
#SuppressWarnings ("unchecked")
public void displayFromExcel (String xlsPath)
{
InputStream inputStream = null;
try
{
inputStream = new FileInputStream (xlsPath);
}
catch (FileNotFoundException e)
{
System.out.println ("File not found in the specified path.");
e.printStackTrace ();
}
POIFSFileSystem fileSystem = null;
try
{
fileSystem = new POIFSFileSystem (inputStream);
HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
HSSFSheet sheet = workBook.getSheetAt (0);
Iterator<HSSFRow> rows = sheet.rowIterator ();
while (rows.hasNext ())
{
HSSFRow row = rows.next ();
if(row.getRowNum()==0 || row.getRowNum()==1){
continue; //just skip the rows if row number is 0 or 1
}
// once get a row its time to iterate through cells.
Iterator<HSSFCell> cells = row.cellIterator ();
while (cells.hasNext ())
{
HSSFCell cell = cells.next ();
System.out.println ("Cell No.: " + cell.getCellNum ());
/*
* Now we will get the cell type and display the values
* accordingly.
*/
switch (cell.getCellType ())
{
case HSSFCell.CELL_TYPE_NUMERIC :
{
// cell type numeric.
System.out.println ("Numeric value: " + cell.getNumericCellValue ());
break;
}
case HSSFCell.CELL_TYPE_STRING :
{
// cell type string.
HSSFRichTextString richTextString = cell.getRichStringCellValue ();
System.out.println ("String value: " + richTextString.getString ());
break;
}
default :
{
// types other than String and Numeric.
System.out.println ("Type not supported.");
break;
}
}
}
}
}
catch (IOException e)
{
e.printStackTrace ();
}
}
public static void main (String[] args)
{
POIExcelReader poiExample = new POIExcelReader ();
String xlsPath = "c://test//test.xls";
poiExample.displayFromExcel (xlsPath);
}
}
Apache POI provides two ways to access the rows and cells in an Excel file. One is an iterator that gives you all the entries, the other is to loop up by index. (POI will also tell you the start/end rows/columns). The iterator is often simpler to use, but both are equally as fast.
If you have specific requirements on rows to fetch, I'd suggest you use the latter. Your code would want to be something like:
int FIRST_ROW_TO_GET = 2; // 0 based
Sheet s = wb.getSheetAt(0);
for (int i = FIRST_ROW_TO_GET; i < s.getLastRowNum(); i++) {
Row row = s.getRow(i);
if (row == null) {
// The whole row is blank
}
else {
for (int cn=row.getFirstCellNum(); cn<row.getLastCellNum(); cn++) {
Cell c = row.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null) {
// The cell is empty
} else {
// Process the cell
}
}
}
}
you can improve Murali N s answer. If you want to skip 40 rows for example, use:
if (currentRow.getRowNum() <= 40) {
continue;
}

Resources