I'm trying to write a method that takes two HSSFSheets (from two different HSSFWorkbooks that are imported via a FileChooser) and makes sure that the name of each Row of Sheet1 (as in the first cell of each row of Sheet1) has to be the same name as each Row of Sheet2. If it's not the case the method has to re-organize Sheet2 so as the names of each Row of Sheet2 should match those of Sheet1.
In the end the method should create and open a new excel file which should contain the reorganized Sheet2. And this is where the problem comes in
public void organizeSheets(HSSFSheet sheet1, HSSFSheet sheet2) throws FileNotFoundException, IOException {
HSSFWorkbook permutationWb = new HSSFWorkbook();
HSSFSheet permutationSheet = permutationWb.createSheet();
short noOfColumns;
HSSFRow testrow = sheet1.getRow(0);
short testcell = testrow.getLastCellNum();
noOfColumns = testcell;
int noOfRows = sheet1.getPhysicalNumberOfRows();
short noOfColumns2;
HSSFRow testrow2 = sheet2.getRow(0);
short testcell2 = testrow2.getLastCellNum();
noOfColumns2 = testcell2;
for (int i = 0; i < noOfRows; i++) {
if (!getValue(sheet1, 0, i).toString().equals(getValue(sheet2, 0, i).toString())) {
System.out.println(getValue(sheet1, 0, i));
System.out.println(getValue(sheet2, 0, i));
int j = 0;
while (!getValue(sheet1, 0, i).toString().equals(getValue(sheet2, 0, j).toString())) {
j = j + 1;
}
HSSFRow transitionRow1 = permutationSheet.createRow(0);
HSSFRow transitionRow2 = permutationSheet.createRow(1);
for (int l=0; l < noOfColumns2; l++) {
transitionRow1.createCell(l);
transitionRow1.getCell(l).setCellValue(getValue(sheet2, l, j));
//System.out.println(transitionRow1.getCell(l));
}
for (int p=0; p < noOfColumns2; p++) {
transitionRow2.createCell(p);
transitionRow2.getCell(p).setCellValue(getValue(sheet2, p, i));
}
for (int k=0; k < noOfColumns2; k++) {
sheet2.getRow(j).getCell(k).setCellValue(getValue(permutationSheet, k, 1).toString());
sheet2.getRow(i).getCell(k).setCellValue(getValue(permutationSheet, k, 0).toString());
}
}
}
sheet2.getWorkbook().write(new FileOutputStream("C:\\Users\\PC HP\\Desktop\\organized.xls"));
sheet2.getWorkbook().close();
Desktop.getDesktop().open(new File("C:\\Users\\PC HP\\Desktop\\organized.xls"));
}
getValue(sheet, row, column) allows me to get the value of the cell whose coordinates are in the arguments of the method.
Here's the error message I'm getting
Exception in thread "main" java.lang.IndexOutOfBoundsException: Block 33 not found
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.getBlockAt(NPOIFSFileSystem.java:486)
at org.apache.poi.poifs.filesystem.NPOIFSStream$StreamBlockByteBufferIterator.next(NPOIFSStream.java:169)
at org.apache.poi.poifs.filesystem.NPOIFSStream$StreamBlockByteBufferIterator.next(NPOIFSStream.java:142)
at org.apache.poi.poifs.filesystem.NDocumentInputStream.readFully(NDocumentInputStream.java:248)
at org.apache.poi.poifs.filesystem.NDocumentInputStream.read(NDocumentInputStream.java:150)
at org.apache.poi.poifs.filesystem.DocumentInputStream.read(DocumentInputStream.java:125)
at org.apache.poi.hpsf.PropertySet.isPropertySetStream(PropertySet.java:336)
at org.apache.poi.hpsf.PropertySet.<init>(PropertySet.java:241)
at org.apache.poi.hpsf.PropertySetFactory.create(PropertySetFactory.java:92)
at org.apache.poi.POIDocument.getPropertySet(POIDocument.java:211)
at org.apache.poi.POIDocument.getPropertySet(POIDocument.java:168)
at org.apache.poi.POIDocument.readProperties(POIDocument.java:141)
at org.apache.poi.POIDocument.getSummaryInformation(POIDocument.java:108)
at org.apache.poi.POIDocument.writeProperties(POIDocument.java:260)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:1377)
at model.main.organizeSheets(main.java:377)
at model.main.main(main.java:42)
Caused by: java.lang.IndexOutOfBoundsException: Unable to read 512 bytes from 17408 in stream of length -1
at org.apache.poi.poifs.nio.ByteArrayBackedDataSource.read(ByteArrayBackedDataSource.java:42)
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.getBlockAt(NPOIFSFileSystem.java:484)
... 16 more
I believe that there is no problem with the actual switch between the rows of Sheet2 (I've tested with prints, I might be wrong if I didn't test enough) and I have no idea how to deal with this situation.
In order to instantiate Sheet2, the code asks the user to chose a workbook from his computer then choose a sheet within the workbook like follows
excelworkbook1 = o.chooseFile1();
Scanner scanner1 = new Scanner(System.in);
int sheetnumber1 = Integer.parseInt(scanner1.nextLine());
excelsheet1 = o.chooseSheet(excelworkbook1, sheetnumber1);
public HSSFWorkbook chooseFile1() throws IOException {
JFrame frame = null;
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(frame);
String filepath = new String();
if (returnVal == JFileChooser.APPROVE_OPTION) {
filepath = fc.getSelectedFile().getCanonicalPath();
setFile1Adress(filepath);
} else {
System.exit(1);
}
FileInputStream file1InputStream;
file1InputStream = new FileInputStream(filepath);
NPOIFSFileSystem file;
file = new NPOIFSFileSystem(file1InputStream);
HSSFWorkbook workbook = new HSSFWorkbook(file.getRoot(), true);
file.close();
return workbook;
}
public HSSFSheet chooseSheet(HSSFWorkbook excelfile, int entry) {
return excelfile.getSheetAt(entry - 1);
}
Related
I want to run selenium-webdriver-java-eclipse, using excel file contains multiple excel sheets with different name(sheet1,sheet2,sheet3,...), i need a for loop help me to do that and read from this sheets.
public class ExcelDataConfig {
XSSFWorkbook wb;
XSSFSheet sheet = null;
public ExcelDataConfig(String Excelpath) throws IOException {
// TODO Auto-generated method stub
try {
File file = new File(Excelpath);
// Create an object of FileInputStream class to read excel file
FileInputStream fis = new FileInputStream(file);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
}
}
public String GetData(int sheetNumber, int Row, int Column) {
Iterator<Row> rowIt=sheet.rowIterator();
DataFormatter formatter = new DataFormatter();
XSSFCell cell = sheet.getRow(Row).getCell(Column);
String data = formatter.formatCellValue(cell);
return data;
}
public int GetRowCount(String sheetNumber) {
int row = wb.getSheet(sheetNumber).getLastRowNum();
row = row + 1;
return row;
}
}
try something like this, it is working for me you need to add the sheet numbers and cell numbers at the places of k and j
enter code here
String filePath="C:\\Users\\USER\\Desktop\\Book1.xlsx";// file path
FileInputStream fis=new FileInputStream(filePath);
Workbook wb=WorkbookFactory.create(fis);
ArrayList<String> ls=new ArrayList<String>();
for(int k=0; k<=3;k++)//k =sheet no
{
Sheet sh=wb.getSheetAt(k);
System.out.println(sh);
// int count=0;
for(int i=0;i<=sh.getLastRowNum();i++)
{
System.out.println("row no:"+i);
for(int j=0; j<=4;j++)//j=column no
{
try {
String values=sh.getRow(i).getCell(j).getStringCellValue().trim();
System.out.println(values);
//condetions
/* if(values.contains("condtn1"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}
if(values.contains("condn2"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}*/
}catch(Exception e){
}
}
}
}
}
}
Please try writing similar to something like this:
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);
}
}
Terms used in method are pretty self explanatory. Let us know if you get stuck or need more info.
I want to create an excel document with 5 sheets, the data for the sheets is dynamic and I have a maximum row limit.
currently my approach is creating one sheet at a time, and filling it with data. I am checking if max rows have been exceeded, and creating a new excel document.
However this will not wait to check if the other sheets are also exceeding the max row limit before creating the new workbook
My code samples
private void populateDetailsSheets(String[] data) throws IOException
{
currentRow = getCurrentRow();
rowCount++;
short cellNumber = 0;
for (String value : data)
{
POIExcelUtil.createCellWithContent(currentRow,value,cellNumber++).setCellStyle(contentStyle);
}
writeToFileOnExhaustingMaxRows();
}
private void writeToFileOnExhaustingMaxRows() throws IOException
{
if(sheet.getLastRowNum() + 2 > Integer.valueOf(SystemProperty.MAX_RECORDS_PER_EXCEL))
{
writeToFile();
rowCount = 0;
createWorkbook();
titleStyle = createTitleStyle();
headerStyle = createHeaderStyle();
columnHeaderStyle = createColumnHeaderStyle();
columnHeaderStyle.setBorderLeft(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderTop(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderRight(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);
contentStyle = createCellStyle();
contentStyle.setBorderLeft(CellStyle.BORDER_THIN);
contentStyle.setBorderTop(CellStyle.BORDER_THIN);
contentStyle.setBorderRight(CellStyle.BORDER_THIN);
contentStyle.setBorderBottom(CellStyle.BORDER_THIN);
rowCount = 0;
createSheet("title sheet");
populateReportSettingsSheet();
rowCount =0;
createSheet(sheetNames[index]);
setColumnWidth();
createColumnHeader();
}
}
I am assuming that you want to jump to next sheet when the sheet one is full. Here the trick.
public class JumpToNewSheet {
private static HSSFSheet allocateNewSheet(HSSFWorkbook wb, String sheetName) {
HSSFSheet sheet = wb.createSheet(sheetName);
/*You can add style here too or write header here*/
return sheet;
}
public HSSFWorkbook exportExcel_xls(MyTable table) {
int cellNumber = 12;
List<TupleData> tuples = table.getTuples();
HSSFWorkbook wb = new HSSFWorkbook();//Whole book
HSSFSheet currentSheet = allocateNewSheet(wb, "SHEET");//Initial sheet
int sheetCounter = 1;//Start at 1 because we already created Initial sheet
int rowCounter = 0;//1st row in sheet
for(TupleData t: tuples) {//Loop through data
if(rowCounter % 65535 == 0) {//Max row reached, build new sheet
//Increase sheetCounter
sheetCounter++;
String new_sheetName = "SHEET_"+sheetCounter;//Name of sheet
currentSheet = allocateNewSheet(wb, new_sheetName);//Point currentSheet to new sheet
//Reset rowCounter to 0
rowCounter = 0;
}
Row row = currentSheet.createRow(rowCounter);
for(int i=0; i <=cellNumber; i++) {
Cell cell = row.createCell(i);
//Write data.......
//.............
}//End inner for loop
rowCounter++;
}//End for loop
}//End exportExcel_xls(MyTable table)
}
I have a following code that reads logins and passwords from xls file starting from the second row(it skips column names) and writes it into a 2d array. But it only works if the sheet doesn't have blank cells in any of the rows. What should i do to make it work with empty cells?
private static Object[][] getUsersFromXls(String sheetName) {
final File excelFile = new File("src//resources//TestData.xls");
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(excelFile);
workbook = new HSSFWorkbook(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
sheet = workbook.getSheet(sheetName);
final int numberOfRows = sheet.getLastRowNum();
final int numberOfColumns = sheet.getRow(0).getLastCellNum();
final String[][] xlsData = new String[numberOfRows][numberOfColumns];
String cellValue;
for (int i = 1; i <= numberOfRows; i++) {
final HSSFRow row = sheet.getRow(i);
for (int j = 0; j < numberOfColumns; j++) {
final HSSFCell cell = row.getCell(j);
final int cellType = cell.getCellType();
if (cellType == HSSFCell.CELL_TYPE_FORMULA) {
throw new RuntimeException("Cannot process a formula. Please change field to result of formula.");
} else {
cellValue = String.valueOf(cell);
xlsData[i - 1][j] = cellValue;
}
}
}
return xlsData;
}
I am trying to build a 2 dimensional array that holds values from a data sheet and then takes those values and displays them within a website application form. I keep getting
The method getCell(int) is undefined for the type HSSFSheet
error and i'm not sure why.
public static void main(String[] args) throws Exception {
File file = new File(
"C:\\Users\\865\\Desktop\\ETAF Selenium\\etaf-selenium-installer\\bin\\Drivers\\64-bit\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
File picassoinput = new File("C:\\Users\\865\\Desktop\\ETAF Selenium\\Data Sheets\\PicassoInputData.xls");
FileInputStream picassofis = new FileInputStream(picassoinput);
HSSFWorkbook picassowb = new HSSFWorkbook(picassofis);
HSSFSheet picassows = picassowb.getSheet("Data");
int rowNum = picassows.getLastRowNum() + 1;
int colNum = picassows.getRow(0).getLastCellNum();
String[][] datainput = new String[rowNum][colNum];
for (int i = 0; i < rowNum; i++) {
HSSFRow row = picassows.getRow(i);
for (int j = 0; j < colNum; j++) {
// the below row of code "HSSFCell cell picassows.getCell(j); is where the error is
// at
HSSFCell cell = picassows.getCell(j);
String value = cellToString(cell);
datainput[i][j] = value;
}
}
Test2 a = new Test2();
a.setUp();
a.testCase();
}
The following are the only relevant parts of your code:
HSSFSheet picassows = picassowb.getSheet("Data");
...
HSSFCell cell = picassows.getCell(j);
As the error states: HSSFSheet does not have HSSFCells!
You probably want:
HSSFCell cell = row.getCell(j);
In the test some fields accepts numbers and it has been given in the excel. But when the data is read from the excel, it reads as decimals. for example number 22 is read as 22.0. I have used apache.poi for the test. How to avoid decimal.
public static void main(String[] args) throws InterruptedException {
try{
FileInputStream input = new FileInputStream("C:Users\\dinu\\Desktop\\RegDetails.xls");
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sheet = wb.getSheet("RegDetails");
for(int count =1; count <= sheet.getLastRowNum(); count++){
HSSFRow row = sheet.getRow(count);
System.out.println("Running Test Case "+row.getCell(0).toString());
runTest(row.getCell(1).toString(),row.getCell(2).toString(),row.getCell(3).toString(),
row.getCell(4).toString(),row.getCell(5).toString(),row.getCell(6).toString(),
row.getCell(7).toString(),row.getCell(8).toString());
}input.close();
}catch (IOException e){
System.out.println("Test data not found.");
}
Use this,it will work...
for (int i = 0; i < sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i + 1);
for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) {
Cell cell = row.getCell(k);
String value;
try {
value = cell.getRichStringCellValue().toString();
} catch (Exception e) {
value = ((XSSFCell) cell).getRawValue();
}
data[i][k] = value;
}