How to read excel file omitting first two rows - excel

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;
}

Related

How to consolidate multiple workbook into one workbook using Apache POI

I have a Java code producing bunch of workbooks and would like to copy all of them into one workbook.
The original answer to this question was posted on:
How to copy a sheet between Excel workbooks in Java
My original idea was to use the cloneSheet method of XSSFWorkbook to do the trick, I was successful in copying the Relations and Drawings however failed to copy the data itself. Why? Because the XSSFSheet's method write and read are protected, I did come up with my own version of XSSFSheet by extending it and making the two methods write and read public, but that would mean I will have to copy and edit every source file using XSSFSheet replacing it with my version of XSSFSheet that would mean too much coding I didn't have that kind of time for the project.
The original answer to this question was posted on:
How to copy a sheet between Excel workbooks in Java
However, my project requirement were different, so I improvised the answer.
I added a method called combine which accepts target workbook, and source workbook.
The methods loops through all the worksheets in the source workbook and adds them to target workbook. The original answer lacked copying of relations and drawing.
Also the workbooks I was to copy from lacked Footer, neede Gridlines to be turned off, and fit to page. So here is my solution
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.POIXMLDocumentPart.RelationPart;
import org.apache.poi.POIXMLException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.POILogger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import com.hcsc.eas.framework.services.logging.Logger;
public class XSSFWorkbookHelper {
static protected Logger logger = Logger.getLogger(XSSFWorkbookHelper.class.getName());
public static void combine(XSSFWorkbook tgt, XSSFWorkbook src) throws InvalidFormatException {
// begin sheets loop
boolean first=true;
String firstSheetName = null;
XSSFSheet tgtSheet = null;
for (int i = 0; i < src.getNumberOfSheets(); i++) {
XSSFSheet srcSheet = src.getSheetAt(i);
String sheetName = srcSheet.getSheetName().replaceAll("_", "-");
if (first) {
firstSheetName = srcSheet.getSheetName();
if (sheetName.equals(firstSheetName)) sheetName = sheetName + "_";
first = false;
}
tgtSheet = tgt.createSheet(sheetName);
copyRelations(tgtSheet, srcSheet);
copySheets(tgtSheet, srcSheet);
} // end sheets loop
tgtSheet = tgt.getSheet(firstSheetName);
if(tgtSheet != null) {
tgt.removeSheetAt(tgt.getSheetIndex(tgtSheet));
}
}
private static void copyRelations(XSSFSheet tgtSheet,XSSFSheet srcSheet) {
// copy sheet's relations
List<RelationPart> rels = srcSheet.getRelationParts();
// if the sheet being cloned has a drawing then rememebr it and re-create it too
XSSFDrawing dg = null;
for(RelationPart rp : rels) {
POIXMLDocumentPart r = rp.getDocumentPart();
// do not copy the drawing relationship, it will be re-created
if(r instanceof XSSFDrawing) {
dg = (XSSFDrawing)r;
continue;
}
addRelation(rp, tgtSheet);
}
try {
for(PackageRelationship pr : srcSheet.getPackagePart().getRelationships()) {
if (pr.getTargetMode() == TargetMode.EXTERNAL) {
tgtSheet.getPackagePart().addExternalRelationship
(pr.getTargetURI().toASCIIString(), pr.getRelationshipType(), pr.getId());
}
}
} catch (InvalidFormatException e) {
throw new POIXMLException("Failed to clone sheet", e);
}
CTWorksheet ct = tgtSheet.getCTWorksheet();
if(ct.isSetLegacyDrawing()) {
logger.warn(POILogger.WARN + "Cloning sheets with comments is not yet supported.");
ct.unsetLegacyDrawing();
}
if (ct.isSetPageSetup()) {
logger.warn(POILogger.WARN + "Cloning sheets with page setup is not yet supported.");
ct.unsetPageSetup();
}
tgtSheet.setSelected(false);
// clone the sheet drawing alongs with its relationships
if (dg != null) {
if(ct.isSetDrawing()) {
// unset the existing reference to the drawing,
// so that subsequent call of tgtSheet.createDrawingPatriarch() will create a new one
ct.unsetDrawing();
}
XSSFDrawing clonedDg = tgtSheet.createDrawingPatriarch();
// copy drawing contents
clonedDg.getCTDrawing().set(dg.getCTDrawing());
clonedDg = tgtSheet.createDrawingPatriarch();
// Clone drawing relations
List<RelationPart> srcRels = srcSheet.createDrawingPatriarch().getRelationParts();
for (RelationPart rp : srcRels) {
addRelation(rp, clonedDg);
}
}
}
private static void addRelation(RelationPart rp, POIXMLDocumentPart target) {
PackageRelationship rel = rp.getRelationship();
if (rel.getTargetMode() == TargetMode.EXTERNAL) {
target.getPackagePart().addRelationship(rel.getTargetURI(), rel.getTargetMode(), rel.getRelationshipType(),
rel.getId());
} else {
XSSFRelation xssfRel = XSSFRelation.getInstance(rel.getRelationshipType());
if (xssfRel == null) {
// Don't copy all relations blindly, but only the ones we know
// about
throw new POIXMLException(
"Can't clone sheet - unknown relation type found: " + rel.getRelationshipType());
}
target.addRelation(rel.getId(), xssfRel, rp.getDocumentPart());
}
}
/**
* #param newSheet
* the sheet to create from the copy.
* #param sheet
* the sheet to copy.
*/
public static void copySheets(XSSFSheet newSheet, XSSFSheet sheet) {
copySheets(newSheet, sheet, true);
}
/**
* #param newSheet
* the sheet to create from the copy.
* #param sheet
* the sheet to copy.
* #param copyStyle
* true copy the style.
*/
public static void copySheets(XSSFSheet newSheet, XSSFSheet sheet, boolean copyStyle) {
setupSheet(newSheet);
int maxColumnNum = 0;
Map<Integer, CellStyle> styleMap = (copyStyle) ? new HashMap<Integer, CellStyle>() : null;
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
XSSFRow srcRow = sheet.getRow(i);
XSSFRow destRow = newSheet.createRow(i);
if (srcRow != null) {
copyRow(sheet, newSheet, srcRow, destRow, styleMap);
if (srcRow.getLastCellNum() > maxColumnNum) {
maxColumnNum = srcRow.getLastCellNum();
}
}
}
for (int i = 0; i <= maxColumnNum; i++) {
newSheet.setColumnWidth(i, sheet.getColumnWidth(i));
}
}
public static void setupSheet(XSSFSheet newSheet) {
newSheet.getFooter().setCenter("&7 _x0000_ A Division of Health Care Service Corporation, a Mutual Legal Reserve Company, \n _x0000_ an Independent Licensee of the Blue Cross and Blue Shield Association");
newSheet.setDisplayGridlines(false);
newSheet.setMargin(Sheet.RightMargin, 0.5 /* inches */ );
newSheet.setMargin(Sheet.LeftMargin, 0.5 /* inches */ );
newSheet.setMargin(Sheet.TopMargin, 0.5 /* inches */ );
newSheet.setMargin(Sheet.BottomMargin, 0.5 /* inches */ );
newSheet.setFitToPage(true);
}
/**
* #param srcSheet
* the sheet to copy.
* #param destSheet
* the sheet to create.
* #param srcRow
* the row to copy.
* #param destRow
* the row to create.
* #param styleMap
* -
*/
public static void copyRow(XSSFSheet srcSheet, XSSFSheet destSheet, XSSFRow srcRow, XSSFRow destRow,
Map<Integer, CellStyle> styleMap) {
try {
// manage a list of merged zone in order to not insert two times a
// merged zone
Set<CellRangeAddressWrapper> mergedRegions = new TreeSet<CellRangeAddressWrapper>();
destRow.setHeight(srcRow.getHeight());
// reckoning delta rows
int deltaRows = destRow.getRowNum() - srcRow.getRowNum();
// pour chaque row
for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) {
XSSFCell oldCell = srcRow.getCell(j); // ancienne cell
XSSFCell newCell = destRow.getCell(j); // new cell
if (oldCell != null) {
if (newCell == null) {
newCell = destRow.createCell(j);
}
// copy chaque cell
copyCell(oldCell, newCell, styleMap);
// copy les informations de fusion entre les cellules
// System.out.println("row num: " + srcRow.getRowNum() + " ,
// col: " + (short)oldCell.getColumnIndex());
CellRangeAddress mergedRegion = getMergedRegion(srcSheet, srcRow.getRowNum(),
(short) oldCell.getColumnIndex());
if (mergedRegion != null) {
// System.out.println("Selected merged region: " +
// mergedRegion.toString());
CellRangeAddress newMergedRegion = new CellRangeAddress(mergedRegion.getFirstRow() + deltaRows,
mergedRegion.getLastRow() + deltaRows, mergedRegion.getFirstColumn(),
mergedRegion.getLastColumn());
// System.out.println("New merged region: " +
// newMergedRegion.toString());
CellRangeAddressWrapper wrapper = new CellRangeAddressWrapper(newMergedRegion);
if (isNewMergedRegion(wrapper, mergedRegions)) {
mergedRegions.add(wrapper);
destSheet.addMergedRegion(wrapper.range);
}
}
}
}
} catch (Exception e) {
//e.printStackTrace();
logger.warn(POILogger.WARN + "merge area failure, happens when a merge area overlaps.");
}
}
/**
* #param oldCell
* #param newCell
* #param styleMap
*/
public static void copyCell(XSSFCell oldCell, XSSFCell newCell, Map<Integer, CellStyle> styleMap) {
if (styleMap != null) {
if (oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()) {
newCell.setCellStyle(oldCell.getCellStyle());
} else {
int stHashCode = oldCell.getCellStyle().hashCode();
CellStyle newCellStyle = styleMap.get(stHashCode);
if (newCellStyle == null) {
newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
styleMap.put(stHashCode, newCellStyle);
}
newCell.setCellStyle(newCellStyle);
}
}
switch (oldCell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case XSSFCell.CELL_TYPE_NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case XSSFCell.CELL_TYPE_BLANK:
newCell.setCellType(XSSFCell.CELL_TYPE_BLANK);
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case XSSFCell.CELL_TYPE_ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case XSSFCell.CELL_TYPE_FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
default:
break;
}
}
/**
* Retrieves cell merge information in the source sheet
* to apply them to the destination sheet ... Get all zones
* merged in the source sheet and look for each of them if she
* find in the current row that we are dealing. If yes, return the object
* CellRangeAddress.
*
* #param sheet
* the sheet containing the data.
* #param rowNum
* the num of the row to copy.
* #param cellNum
* the num of the cell to copy.
* #return the CellRangeAddress created.
*/
public static CellRangeAddress getMergedRegion(XSSFSheet sheet, int rowNum, short cellNum) {
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress merged = sheet.getMergedRegion(i);
if (merged.isInRange(rowNum, cellNum)) {
return merged;
}
}
return null;
}
/**
* Check that the merged region has been created in the destination sheet.
*
* #param newMergedRegion
* the merged region to copy or not in the destination sheet.
* #param mergedRegions
* the list containing all the merged region.
* #return true if the merged region is already in the list or not.
*/
private static boolean isNewMergedRegion(CellRangeAddressWrapper newMergedRegion,
Set<CellRangeAddressWrapper> mergedRegions) {
return !mergedRegions.contains(newMergedRegion);
}
}
class CellRangeAddressWrapper implements Comparable<CellRangeAddressWrapper> {
public CellRangeAddress range;
/**
* #param theRange
* the CellRangeAddress object to wrap.
*/
public CellRangeAddressWrapper(CellRangeAddress theRange) {
this.range = theRange;
}
/**
* #param o
* the object to compare.
* #return -1 the current instance is prior to the object in parameter, 0:
* equal, 1: after...
*/
public int compareTo(CellRangeAddressWrapper o) {
if (range.getFirstColumn() < o.range.getFirstColumn() && range.getFirstRow() < o.range.getFirstRow()) {
return -1;
} else if (range.getFirstColumn() == o.range.getFirstColumn() && range.getFirstRow() == o.range.getFirstRow()) {
return 0;
} else {
return 1;
}
}
}

testNG multiple dataproviders passing data to one class having multiple test methods

EDIT1: I have an ExcelUtility.java class to get cell data from it and pass it on to the tests methods in my test class.
I am reading from 1 excel file.
The excel file has 3 worksheets.
Every worksheet has 1 unique working table inside.
I have 1 Test class.
The test class has 3 test methods.
The test class contains 3 dataProviders.
All dataProviders differ in the worksheet name and working table name.
The tests in the test class are written in the following manner:
#Test(priority = 0, dataProvider = "dp1")
public void test01(String...strings){
}
#Test(priority = 1, dataProvider = "dp2")
public void test02(String...strings){
}
#Test(priority = 2, dataProvider = "dp3")
public void test03(String...strings){
}
I have the following java class to read from XLSX file using apache poi jars:
public class ExcelUtility {
private static XSSFWorkbook ExcelWBook;
private static XSSFSheet ExcelWSheet;
/*
* Set the File path, open Excel file
* #params - Excel Path and Sheet Name
*/
public static void setExcelFile(String path, String sheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(path);
// Access the excel data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(sheetName);
} catch (Exception e) {
throw (e);
}
}
public static String[][] getTestData(String tableName) {
String[][] testData = null;
try {
// Handle numbers and strings
DataFormatter formatter = new DataFormatter();
XSSFCell[] boundaryCells = findCells(tableName);
XSSFCell startCell = boundaryCells[0];
XSSFCell endCell = boundaryCells[1];
int startRow = startCell.getRowIndex() + 1;
int endRow = endCell.getRowIndex() - 1;
int startCol = startCell.getColumnIndex() + 1;
int endCol = endCell.getColumnIndex() - 1;
testData = new String[endRow - startRow + 1][endCol - startCol + 1];
for (int i=startRow; i<endRow+1; i++) {
for (int j=startCol; j<endCol+1; j++) {
// testData[i-startRow][j-startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
Cell cell = ExcelWSheet.getRow(i).getCell(j);
testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
public static XSSFCell[] findCells(String tableName) {
DataFormatter formatter = new DataFormatter();
String pos = "begin";
XSSFCell[] cells = new XSSFCell[2];
for (Row row : ExcelWSheet) {
for (Cell cell : row) {
// if (tableName.equals(cell.getStringCellValue())) {
if (tableName.equals(formatter.formatCellValue(cell))) {
if (pos.equalsIgnoreCase("begin")) {
cells[0] = (XSSFCell) cell;
pos = "end";
} else {
cells[1] = (XSSFCell) cell;
}
}
}
}
return cells;
}
}
In order to read from the excel file I have organized the test methods in the following manner:
#DataProvider(name = "dp1")
public Object[][] dp1() throws IOException {
Object[][] testData = new Object[0][];
try {
ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page1");
testData = ExcelUtility.getTestData("P1");
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
#DataProvider(name = "dp2")
public Object[][] dp2() throws IOException {
Object[][] testData = new Object[0][];
try {
ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page2");
testData = ExcelUtility.getTestData("P2");
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
#DataProvider(name = "dp3")
public Object[][] dp3() throws IOException {
Object[][] testData = new Object[0][];
try {
ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page3");
testData = ExcelUtility.getTestData("P3");
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
#Test(priority = 0, dataProvider = "dp1")
public void test01(String...strings){
//read data from excel and pass the value to the strings added as arguments in the method above
}
#Test(priority = 1, dataProvider = "dp2")
public void test02(String...strings){
}
#Test(priority = 2, dataProvider = "dp3")
public void test03(String...strings){
}
What I would like to do is the following:
Read first row data from sheet1, pass it to test1, continue to test2
Read first row data from sheet2, pass it to test2, continue to test3
Read first row data from sheet3, pass it to test3, continue to test1
Read second row data from sheet 1, pass it to test1, continue to test2
And so on, depending of number of rows in the excel sheets.
What happens is:
The first test is executed, reads worksheet 1, row 1.
The first test is executed, reads worksheet 1, row 2.
The second test is executed, reads worksheet 2, row 1.
The second test is executed, reads worksheet 2, row 2.
All tests fail because they are dependable from each other, that is why I set execution priority.
Should I change something in the Test class, or something in the ExcelUtility.java class should be changed?
Thank you in advance!
See files related to the commit
It creates testng.xml based on xlsx with test data.

How to edit data with dynamic TableView with dynamic column in JAVAFX

Today This is the demo to show data from CSV for DAT file without make custom class on tableView in JavaFX 2.0. I call this TableView as Dynamic TableView because the tableview automatically manages the columns and rows.
On my research about the editable on tableView we must have a custom class and implement it to tableView to show as this demo ==> http://docs.oracle.com/javafx/2/ui_controls/table-view.htm
But in this case I can not do it because we don't know how many column example with csv file or .dat file.... I want to do editable on this tableView in this case by add TextField into TableCell. How does it do without make custom class (because you do not how many column ...), and if it must make custom class then how about the design of custom class for this case?
Could you please help me?
private void getDataDetailWithDynamic() {
tblView.getItems().clear();
tblView.getColumns().clear();
tblView.setPlaceholder(new Label("Loading..."));
// #Override
try {
File aFile = new File(txtFilePath.getText());
InputStream is = new BufferedInputStream(new FileInputStream(aFile));
Reader reader = new InputStreamReader(is, "UTF-8");
BufferedReader in = new BufferedReader(reader);
final String headerLine = in.readLine();
final String[] headerValues = headerLine.split("\t");
for (int column = 0; column < headerValues.length; column++) {
tblView.getColumns().add(
createColumn(column, headerValues[column]));
}
// Data:
String dataLine;
while ((dataLine = in.readLine()) != null) {
final String[] dataValues = dataLine.split("\t");
// Add additional columns if necessary:
for (int columnIndex = tblView.getColumns().size(); columnIndex < dataValues.length; columnIndex++) {
tblView.getColumns().add(createColumn(columnIndex, ""));
}
// Add data to table:
ObservableList<StringProperty> data = FXCollections
.observableArrayList();
for (String value : dataValues) {
data.add(new SimpleStringProperty(value));
}
tblView.getItems().add(data);
}
} catch (Exception ex) {
System.out.println("ex: " + ex.toString());
}
for(int i=0; i<tblView.getColumns().size(); i++) {
TableColumn col = (TableColumn)tblView.getColumns().get(i);
col.setPrefWidth(70);
}
}
private TableColumn createColumn(
final int columnIndex, String columnTitle) {
TableColumn column = new TableColumn(DefaultVars.BLANK_CHARACTER);
String title;
if (columnTitle == null || columnTitle.trim().length() == 0) {
title = "Column " + (columnIndex + 1);
} else {
title = columnTitle;
}
Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>() {
#Override
public TableCell call(TableColumn p) {
System.out.println("event cell");
EditingCellData cellExtend = new EditingCellData();
return cellExtend;
}
};
column.setText(title);
column.setCellValueFactory(cellFactory);
return column;
}
Thanks for your reading.
This is the best way to resolve it ==> https://forums.oracle.com/message/11216643#11216643
I'm really thank for your reading about that.
Thanks

how to get last row of excel in POI and append blank row?

how to get last row of excel in POI and append blank row and write the next record after the blank row
Below is my code snippet
public class ResultSetToExcel {
private HSSFWorkbook workbook;
private HSSFSheet sheet;
private HSSFFont boldFont;
private HSSFDataFormat format;
private ResultSet resultSet;
private FormatType[] formatTypes;
public ResultSetToExcel(ResultSet resultSet, FormatType[] formatTypes, String sheetName) {
workbook = new HSSFWorkbook();
this.resultSet = resultSet;
sheet = workbook.createSheet(sheetName);
boldFont = workbook.createFont();
boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
format = workbook.createDataFormat();
this.formatTypes = formatTypes;
}
public ResultSetToExcel(ResultSet resultSet, String sheetName) {
this(resultSet, null, sheetName);
}
private FormatType getFormatType(Class _class) {
if (_class == Integer.class || _class == Long.class) {
return FormatType.INTEGER;
} else if (_class == Float.class || _class == Double.class) {
return FormatType.FLOAT;
} else if (_class == Timestamp.class || _class == java.sql.Date.class) {
return FormatType.DATE;
} else {
return FormatType.TEXT;
}
}
public void generate(OutputStream outputStream) throws Exception {
try {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
if (formatTypes != null && formatTypes.length != resultSetMetaData.getColumnCount()) {
throw new IllegalStateException("Number of types is not identical to number of resultset columns. "
+ "Number of types: " + formatTypes.length + ". Number of columns: "
+ resultSetMetaData.getColumnCount());
}
int currentRow = 0;
HSSFRow row = sheet.createRow(currentRow);
int numCols = resultSetMetaData.getColumnCount();
boolean isAutoDecideFormatTypes;
if (isAutoDecideFormatTypes = (formatTypes == null)) {
formatTypes = new FormatType[numCols];
}
for (int i = 0; i < numCols; i++) {
String title = resultSetMetaData.getColumnName(i + 1);
writeCell(row, i, title, FormatType.TEXT, boldFont);
if (isAutoDecideFormatTypes) {
Class _class = Class.forName(resultSetMetaData.getColumnClassName(i + 1));
formatTypes[i] = getFormatType(_class);
}
}
currentRow++; // Write report rows
while (resultSet.next()) {
row = sheet.createRow(currentRow++);
for (int i = 0; i < numCols; i++) {
Object value = resultSet.getObject(i + 1);
writeCell(row, i, value, formatTypes[i]);
}
}
// Autosize columns
for (int i = 0; i < numCols; i++) {
sheet.autoSizeColumn((short) i);
}
workbook.write(outputStream);
} finally {
outputStream.close();
}
}
public void generate(File file) throws Exception {
generate(new FileOutputStream(file));
}
private void writeCell(HSSFRow row, int col, Object value, FormatType formatType) throws NestableException {
writeCell(row, col, value, formatType, null, null);
}
private void writeCell(HSSFRow row, int col, Object value, FormatType formatType, HSSFFont font)
throws NestableException {
writeCell(row, col, value, formatType, null, font);
}
private void writeCell(HSSFRow row, int col, Object value, FormatType formatType, Short bgColor, HSSFFont font)
throws NestableException {
HSSFCell cell = HSSFCellUtil.createCell(row, col, null);
if (value == null) {
return;
}
if (font != null) {
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
cell.setCellStyle(style);
}
switch (formatType) {
case TEXT:
cell.setCellValue(value.toString());
break;
case INTEGER:
cell.setCellValue(((Number) value).intValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT, HSSFDataFormat
.getBuiltinFormat(("#,##0")));
break;
case FLOAT:
cell.setCellValue(((Number) value).doubleValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT, HSSFDataFormat
.getBuiltinFormat(("#,##0.00")));
break;
case DATE:
cell.setCellValue((Timestamp) value);
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT, HSSFDataFormat
.getBuiltinFormat(("m/d/yy")));
break;
case MONEY:
cell.setCellValue(((Number) value).intValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT, format
.getFormat("($#,##0.00);($#,##0.00)"));
break;
case PERCENTAGE:
cell.setCellValue(((Number) value).doubleValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT, HSSFDataFormat
.getBuiltinFormat("0.00%"));
}
if (bgColor != null) {
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.FILL_FOREGROUND_COLOR, bgColor);
HSSFCellUtil
.setCellStyleProperty(cell, workbook, HSSFCellUtil.FILL_PATTERN, HSSFCellStyle.SOLID_FOREGROUND);
}
}
public enum FormatType {
TEXT, INTEGER, FLOAT, DATE, MONEY, PERCENTAGE
}
}
And class implementing the above code
ResultSetToExcel resultSetToExcel = new ResultSetToExcel(iResultSet, csv_file_name);
int fileCount = 1;
while (true) {
boolean done = resultSetToExcel.generate(new File(csv_file_path+ csv_file_name));
if (done) break;
csv_file_name = csv_file_name + "_" + fileCount + ".xls";
fileCount++;
}
Edit:
I used below snippet
InputStream myxls = new FileInputStream("test.xls");
Workbook book = new HSSFWorkbook(myxls);
Sheet sheet = book.getSheetAt(0);
System.out.println(sheet.getLastRowNum());
But I get this error
java.io.IOException: Unable to read entire header; 0 bytes read; expected 512 bytes
The key bit is the exception is the number 0:
java.io.IOException: Unable to read entire header; 0 bytes read; expected 512 bytes
POI went to read the 512 byte header that should be at the start of the file, but found 0 bytes in the file - your file is empty.
Make sure you're passing in the correct filename to load. (You mention struts in your tag, you might not be in the directory you expected to be when running...)
Also, I'd suggest a slight improvement to your code. You have a file, and you're using the common interfaces, so you should change how you load the workbook. Instead of your current:
InputStream myxls = new FileInputStream("test.xls");
Workbook book = new HSSFWorkbook(myxls);
You'd be much better off with
Workbook book = WorkbookFactory.create(new File("test.xls"));
Loading directly from a file, rather than going via an InputStream, will give better performance and a lower memory footprint. By using the WorkbookFactory, your code can work for both XLS and XLSX files.

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

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.

Resources