Read the Adjacent cell value in Excel Sheet using Java - java

I have an excel sheet and I want to give it a string input and have the java code look for the input in the excel sheet. And when it finds it, it prints the adjacent cell (the one on its right).
This code just gives me all the excel sheet values. But what I want is for it to give me a specific value.
This is my code:
package readfiles;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class LeerArchivosDeExcel {
public LeerArchivosDeExcel(File fileName){
List cellData = new ArrayList();
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
XSSFSheet hssfSheet = workBook.getSheetAt(0);
Iterator rowIterator = hssfSheet.rowIterator();
while(rowIterator.hasNext()){
XSSFRow hssfRow = (XSSFRow) rowIterator.next();
Iterator iterator = hssfRow.cellIterator();
List cellTemp = new ArrayList();
while (iterator.hasNext()){
XSSFCell hssfCell = (XSSFCell) iterator.next();
cellTemp.add(hssfCell);
}
cellData.add(cellTemp);
}
} catch (Exception e) {
e.printStackTrace();
}
obtener(cellData);
}
private void obtener(List cellDataList){
for (int i = 0; i < cellDataList.size(); i++) {
List cellTempList = (List) cellDataList.get(i);
for (int j = 0; j < cellTempList.size(); j++) {
XSSFCell hssfCell = (XSSFCell) cellTempList.get(j);
String stringCellValue = hssfCell.toString();
System.out.print(stringCellValue+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
File f = new File ("/Users/sushi/Documentos/BD2/Libro.xlsx");
Scanner input = new Scanner(System.in);
if (f.exists()){
LeerArchivosDeExcel obj = new LeerArchivosDeExcel(f);
}
}
}

You can write a method like this:
public String getAdjacentCellValue(Sheet sheet, String searchText) {
DataFormatter formatter = new DataFormatter();
for (Row row : sheet) {
for (Cell cell : row) {
if (searchText.equals(formatter.formatCellValue(cell))) {
// text matches the string cell value,
// so find the adjacent cell
Cell adjacentCell = row.getCell(cell.getColumnIndex() + 1);
if (adjacentCell == null) {
// cell does not exist in excel model yet,
// so it is considered a blank cell by default
return "";
} else {
// cell exists in excel model
// return the value
return formatter.formatCellValue(adjacentCell);
}
}
}
}
// search text not found
return null;
}
Some notes are appropriate here:
You can iterate the worksheet this succinctly because the Sheet interface extends Iterable<Row> and the Row interface extends Iterable<Cell>.
Use DataFormatter to read a cell's string value becausecell.getStringCellValue() will not work if the cell type is NUMERIC, for example. Additional configuration will be necessary if the cell is a formula cell.
The method invocation row.getCell(cell.getColumnIndex() + 1) may return null. Internally, Excel assumes that all cells in a sheet are blank cells unless otherwise specified. It only stores cells that have been explicitly edited. If the cell has never been created POI returns null. This is not unusual for a typical worksheet.

Related

Getting Exception when reorder RowLabel when hiding the Subtotal -Apache POI

As per below code i dont want to add addRowLabel(1) but need addRowLabel(2) . After running the application and open the pivot table its giving exception but if you add addRowLabel(1)(currently commented) its working as expected. This is happening after adding the logic to hide Subtotal. Is this is the expected behaviour of apache POI or It can be fixed?
Please find the code below.
Note: This issue comes when hiding subtotal.
package com.test.pivottables;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
class TestPivotTables {
public static void main(String[] args) throws IOException{
Workbook wb = new XSSFWorkbook();
String[][] data = new String[][]{{"STATUS","PASSED","DATA","VALUE"},
{"BLUE","Y","TTT","20"},
{"RED","N","UUU","10"},{"BLUE","N","PPP","30"}};
XSSFSheet sheet = (XSSFSheet) wb.createSheet("data");
XSSFSheet pivot = (XSSFSheet) wb.createSheet("summary");
for(String[] dataRow : data){
XSSFRow row = sheet.createRow(sheet.getPhysicalNumberOfRows());
for(String dataCell : dataRow){
XSSFCell cell =
row.createCell(row.getPhysicalNumberOfCells());
cell.setCellValue(dataCell);
}
}
XSSFTable table = sheet.createTable();
CTTable cttable = table.getCTTable();
table.setDisplayName("table");
cttable.setRef("A1:D4");
cttable.setId(1);
CTTableColumns columns = cttable.addNewTableColumns();
columns.setCount(3);
int i = 1;
for (String colName : data[0]){
CTTableColumn column = columns.addNewTableColumn();
column.setId(++i);
column.setName(colName);
}
XSSFPivotTable pivotTable = pivot.createPivotTable(new
AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007),
new CellReference("A4"), sheet);
pivotTable.addRowLabel(0);
pivotTable.addRowLabel(2);
//pivotTable.addRowLabel(1);
List<Integer> iterList = new ArrayList<Integer>();
iterList.add(0);
iterList.add(2);
//iterList.add(1);
pivotTable.getCTPivotTableDefinition().setRowHeaderCaption("Colour");
for (int j=0;j<iterList.size();j++) {
CTPivotField ctPivotField =
pivotTable.getCTPivotTableDefinition().getPivotFields().
getPivotFieldList().get(iterList.get(j));
for (i = 0; i < sheet.getLastRowNum()-1; i++) {
if(ctPivotField.getItems().getItemArray(i)!=null) {
ctPivotField.getItems().getItemArray(i).unsetT();
ctPivotField.getItems().getItemArray(i).setX((long)i);
}
}
for (i = sheet.getLastRowNum(); i > sheet.getLastRowNum()-2; i--)
{
if(ctPivotField.getItems().getItemArray(i)!=null) {
ctPivotField.getItems().removeItem(i);
}
}
ctPivotField.getItems().setCount(2);
Set<String> collection = new HashSet<String>();
int ctr = 0;
Row row = null;
Cell cell = null;
boolean isNull = false;
do{
try{
row = sheet.getRow(ctr);
cell = row.getCell(0);
collection.add(cell.toString());
ctr++;
} catch(Exception e) {
isNull = true;
}
}while(isNull!=true);
if(collection!=null && collection.size()>0) {
Iterator value = collection.iterator();
while (value.hasNext()) {
pivotTable.getPivotCacheDefinition().
getCTPivotCacheDefinition().getCacheFields().
getCacheFieldList().get(j).getSharedItems().addNewS().
setV(value.next().toString());
}
}
ctPivotField.setAutoShow(false);
ctPivotField.setDefaultSubtotal(false);
ctPivotField.setSubtotalTop(false);
ctPivotField.setSubtotalCaption(null);
ctPivotField.setCompact(false);
}
System.out.println("----end---");
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 3, "test");
FileOutputStream fileOut = new FileOutputStream("pivotsample1.xlsx");
wb.write(fileOut);
wb.close();
}}
The problem is how you are building the pivot table definition and the pivot cache definition. This must be done because apache poi creates as much fields for each row label as rows are in the pivot table data range. This is wrong when special settings shall be made for pivot fields. You try to do that, but you do it wrong.
I cannot go into detail where exactly you go wrong because that would be too much effort. But what needs to be done is:
For each column which is row label:
Determine unique labels in that column. This is necessary to build
the cache.
Then build pivot table and cache.
For each unique label:
Build pivot field item as numbered item.
Build a cache definition which has a shared element for this label.
Then remove further items from pivot table definition. But leave one default element there, if there should be subtotals. If not, then not.
Complete example:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.*;
import java.io.*;
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.List;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
class TestPivotTables {
public static void main(String[] args) throws IOException{
Workbook wb = new XSSFWorkbook();
String[][] data = new String[][]{
{"STATUS","PASSED","DATA","VALUE"},
{"BLUE","Y","TTT","20"},
{"RED","N","UUU","10"},
{"BLUE","N","PPP","30"}
};
XSSFSheet sheet = (XSSFSheet) wb.createSheet("data");
XSSFSheet pivot = (XSSFSheet) wb.createSheet("summary");
for(String[] dataRow : data){
XSSFRow row = sheet.createRow(sheet.getPhysicalNumberOfRows());
for(String dataCell : dataRow){
XSSFCell cell = row.createCell(row.getPhysicalNumberOfCells());
cell.setCellValue(dataCell);
}
}
AreaReference areaReference = new AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007);
XSSFPivotTable pivotTable = pivot.createPivotTable(areaReference, new CellReference("A4"), sheet);
pivotTable.getCTPivotTableDefinition().setRowHeaderCaption("Colour");
List<Integer> iterList = new ArrayList<Integer>();
iterList.add(0);
iterList.add(2);
iterList.add(1);
for (Integer j : iterList) {
//create row label - apache poi creates as much fields for each as rows are in the pivot table data range
pivotTable.addRowLabel(j);
//determine unique labels in column j
TreeSet<String> uniqueItems = new java.util.TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
for (int r = areaReference.getFirstCell().getRow()+1; r < areaReference.getLastCell().getRow()+1; r++) {
uniqueItems.add(sheet.getRow(r).getCell(j).getStringCellValue());
}
System.out.println(uniqueItems);
//build pivot table and cache
CTPivotField ctPivotField = pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(j);
int i = 0;
for (String item : uniqueItems) {
//take the items as numbered items: <item x="0"/><item x="1"/>
ctPivotField.getItems().getItemArray(i).unsetT();
ctPivotField.getItems().getItemArray(i).setX((long)i);
//build a cache definition which has shared elements for those items
//<sharedItems><s v="BLUE"/><s v="RED"/></sharedItems>
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(j)
.getSharedItems().addNewS().setV(item);
i++;
}
ctPivotField.setAutoShow(false);
ctPivotField.setDefaultSubtotal(false);
//ctPivotField.setSubtotalTop(false);
//ctPivotField.setSubtotalCaption(null);
ctPivotField.setCompact(false);
//remove further items
if (ctPivotField.getDefaultSubtotal()) i++; //let one default item be if there shall be subtotals
for (int k = ctPivotField.getItems().getItemList().size()-1; k >= i; k--) {
ctPivotField.getItems().removeItem(k);
}
ctPivotField.getItems().setCount(i);
}
System.out.println("----end---");
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 3, "test");
FileOutputStream fileOut = new FileOutputStream("pivotsample1.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

Can I traverse through an excel file using Indexes when working with Apache POI?

Please excuse me if I am not clear. English is not my first language.
I'm trying to write a code where I can traverse through the first row of an excel file until I find the column labeled 'Comments'. I want to run some action on the text in that column and then save the result in a new column at the end of the file. Can I traverse the xlsx file in a manner similar to indexes? And if so, how can I jump straight to a cell using that cell's coordinates?
public static void main(String[] args) throws IOException {
File myFile = new File("temp.xlsx");
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
#SuppressWarnings("resource")
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String comment = cell.toString();
if (comment.equals("Comments"))
{
System.out.println("Hello");
}
}
}
}
For the question "Wanted to go to the second column's 3rd row I could use coordinates like (3, 2)?":
Yes this is possible using CellUtil. Advantages over the methods in Sheet and Row are that CellUtil methods are able getting the cell if it exists already or creating the cell if it not already exists. So existing cells will be respected instead simply new creating them and so overwriting them.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import java.util.concurrent.ThreadLocalRandom;
public class CreateExcelCellsByIndex {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
//put content in R3C2:
Cell cell = CellUtil.getCell(CellUtil.getRow(3-1, sheet), 2-1); //-1 because apache poi's row and cell indexes are 0 based
cell.setCellValue("R3C2");
//put content in 10 random cells:
for (int i = 1; i < 11; i++) {
int r = ThreadLocalRandom.current().nextInt(4, 11);
int c = ThreadLocalRandom.current().nextInt(1, 6);
cell = CellUtil.getCell(CellUtil.getRow(r-1, sheet), c-1);
String cellcontent = "";
if (cell.getCellTypeEnum() == CellType.STRING) {
cellcontent = cell.getStringCellValue() + " ";
}
cell.setCellValue(cellcontent + i + ":R"+r+"C"+c);
}
workbook.write(new FileOutputStream("CreateExcelCellsByIndex.xlsx"));
workbook.close();
}
}
FileInputStream file = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
Map<Integer, List<String>> data = new HashMap<>();
int i = 0;
for (Row row : sheet) {
data.put(i, new ArrayList<String>());
for (Cell cell : row) {
switch (cell.getCellTypeEnum()) {
case STRING: ... break;
case NUMERIC: ... break;
case BOOLEAN: ... break;
case FORMULA: ... break;
default: data.get(new Integer(i)).add(" ");
}
}
i++;
}
I'm not sure what you mean by 2D index, but a Cell knows which column it belongs to so something like this should work:
...
Cell cell = cellIterator.next();
String comment = cell.toString();
int sourceColumnIndex = -1;
if (comment.equals("Comments")) {
System.out.println("Hello");
sourceColumnIndex = cell.getColumnIndex();
}
....
Similarly, define something like int targetColumnIndex to represent the column which will have the result from processing all the cells from the sourceColumnIndex column.

How to access excel cell using cell name with java [duplicate]

I am writing a Java program to read data from excel sheet (having XLSX extension) using Apache POI library. I am able to iterate through all the cells and get all the values. But I am unable to get a specific cell value, say E10.
Is there any way to do this?
Please see the code below that I used for iterating through the cells.
package application;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadFromXLSX {
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:\\Test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
}
}
System.out.println();
}
}
}
For example, to get E10 of the first worksheet:
wb.getSheetAt(0).getRow(9).getCell(4);
Note: subtract one because the indices are null-based.
You can also use this convenience method to map E to 4.
wb.getSheetAt(0).getRow(9).getCell(CellReference.convertColStringToIndex("E"));
To get a value from a specific cell in excel you can use the below code line.
wb.getSheetAt(0).getRow(1).getCell(1);
XSSFSheet has the method getRow(int rownum)
It returns the logical row ( 0-based). If you ask for a row that is not defined you get a null. This is to say row 4 represents the fifth row on a sheet.
Once you get the row, you can call getCell(int cellnum) method of XSSFRow object. It returns the cell at the given (0 based) index.
Just version-up the getCell method
public XSSFCell getCell(String cellName){
Pattern r = Pattern.compile("^([A-Z]+)([0-9]+)$");
Matcher m = r.matcher(cellName);
XSSFWorkbook wb = new XSSFWorkbook();
if(m.matches()) {
String columnName = m.group(1);
int rowNumber = Integer.parseInt(m.group(2));
if(rowNumber > 0) {
return wb.getSheetAt(0).getRow(rowNumber-1).getCell(CellReference.convertColStringToIndex(columnName));
}
}
return null;
}
Now you can get the cell easily by this line
getCell("E10")
public class XmlFileRead {
public static void main(String[] args) throws IOException {
FileInputStream fi = new FileInputStream("abc.xls");
ArrayList<EmployeeVo> al = new ArrayList<>();
EmployeeVo evo = null;
Scanner scanner = null;
Workbook wb = new XSSFWorkbook(fi);
Sheet sh = wb.getSheet("Sheet0");
int starRow = sh.getFirstRowNum();
int endRow = sh.getLastRowNum();
for (int i = starRow + 1; i < endRow; i++) {
scanner = new Scanner(System.in);
evo = new EmployeeVo();
Cell c = wb.getSheetAt(0).getRow(i).getCell(1);
evo.setEmployeeId((int) c.getNumericCellValue());
Cell c2 = wb.getSheetAt(0).getRow(i).getCell(2);
evo.setEmployeeName(c2.toString());
// add to collection
al.add(evo);
} // for
al.forEach(i -> {
System.out.println(i.getEmployeeId() + " " + i.getEmployeeName());
});
}
}

Print the value of 10 and 11 column from excel using java

I have code to print all the values of excel cells but it's ignoring the blank cells. Is there any way to print the value of blank cell (null) as well?
And also is it possible to print particular 2 specific columns (with blank cells) like 10th and 11th column?
Below is my code. Please suggest what can i change in below code?
package excel;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Excel
{
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\Users\\gur29175\\Desktop\\1.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
System.out.print(cell.getStringCellValue() + "\t");
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Row row = rowIterator.next();
for(int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
if(cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
// handle not null values
}else{
// handle null values
}
}

Exception in thread "main" java.lang.IllegalArgumentException: Sheet index (0) is out of range (0..-1)

i want to read the 2010 excel file in java using apache poi api ... but it gives me an error
Exception in thread "main" java.lang.IllegalArgumentException: Sheet index (0) is out of range (0..-1)
i am using xssf
but if i want to get the data from old format of the excel then it works fine by sing HSSF ..
i dont know what is going with XSSF..here is my code ..plz help me in it.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* This java program is used to read the data from a Excel file and display them
* on the console output.
*
* #author dhanago
*/
public class xssff {
/** Creates a new instance of POIExcelReader */
public xssff() {
}
/**
* This method is used to display the Excel content to command line.
*
* #param xlsPath
*/
#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();
}
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.getSheetAt(1);
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
XSSFRow row = (XSSFRow) rows.next();
// display row number in the console.
System.out.println();
// once get a row its time to iterate through cells.
Iterator<Cell> cells = row.cellIterator();
while (cells.hasNext()) {
XSSFCell cell = (XSSFCell) cells.next();
/*
* Now we will get the cell type and display the values
* accordingly.
*/
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_NUMERIC: {
// cell type numeric.
System.out.print(cell.getNumericCellValue() + "\t\t\t");
break;
}
case XSSFCell.CELL_TYPE_STRING: {
// cell type string.
XSSFRichTextString richTextString = cell
.getRichStringCellValue();
System.out.print(richTextString.getString() + "\t\t\t");
break;
}
default: {
// types other than String and Numeric.
System.out.println("Type not supported.");
break;
}
}
}
}
}
/**
* The main executable method to test displayFromExcel method.
*
* #param args
*/
public static void main(String[] args) {
xssff poiExample = new xssff();
String xlsPath = "c://temp//data.xlsx";
poiExample.displayFromExcel(xlsPath);
}
}
Ok I've found your problem, you're creating a new book with no sheets
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.getSheetAt(1); //error here, the workBook book has NO sheets!
You should create the book based in the InputStream
XSSFWorkbook workBook = WorkbookFactory.create(new PushbackInputStream(inputStream));
XSSFSheet sheet = workBook.getSheetAt(1);
Or even easier, just pass the file name to create the book:
XSSFWorkbook workBook = new XSSFWorkbook(xlsPath);
XSSFSheet sheet = workBook.getSheetAt(1);
Try this:
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);
XSSFRow row1 = sheet.createRow(0);
and that function is:
private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
XSSFSheet sheet = null;
int count = 0;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
String sName = wb.getSheetName(i);
if (sName.startsWith(prefix))
count++;
}
if (count > 0) {
sheet = wb.createSheet(prefix + count);
} else
sheet = wb.createSheet(prefix);
if (isHidden)
wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);
return sheet;
}

Categories

Resources