java excel read one column - java

I have a column (B) that I need to take all the values between B3 and B20
this is my code
try {
OPCPackage fs;
fs = OPCPackage.open(new File(getFilePath()));
XSSFWorkbook wb = new XSSFWorkbook(fs);
XSSFSheet sheet = wb.getSheet("Master column name - Used Car");
XSSFRow row;
CellReference cr = new CellReference("B3");
row = sheet.getRow(4);
System.out.println(row);
but as you see, i am getting one value, i didn't know how to get the values for cells B3 until B20
could you help please

have you tried replacing this line:
CellReference cr = new CellReference("B3");
with:
AreaReference ar = new AreaReference("B3:B20");
i.e.
AreaReference ar = new AreaReference("B3:B20");
for (cr : ar.getAllReferencedCells()) {
System.out.print(cr.formatAsString());
System.out.print(" - ");
}
System.out.println();

To read values of certain column or cell from excel you might try this
public static void readFromExcel2(){
try{
FileInputStream file = new FileInputStream(new File("java_excel.xlsx"));//place path of your excel file
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(1);//which sheet you want to read
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()){
Cell cell = cellIterator.next();
if(cell.getColumnIndex()<2&&(cell.getRowIndex()>=3&&cell.getRowIndex()<=20)) {
{
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print((int) cell.getNumericCellValue()+" \t" );
break;
case Cell.CELL_TYPE_BLANK:
System.out.print(" ");
break;
case Cell.CELL_TYPE_STRING: {
System.out.print(cell.getStringCellValue());
}
}
}
}
}
System.out.println(" ");
}
file.close();
}catch (Exception e){
e.printStackTrace();
}
}
}

Related

How to copy a particular row from xsls file and export it to new xlsx file using Apache poi?

I have a folder with 216 xsls files. My logic is to loop throw the folder and read every file, copy the first row of each file and write that row to a new .xsls file.
I want to copy the first row without iterating throw the row and read every cell? for example, if you copy the first line in the .txt file or .csv file.
Also, this is a very slow process. Do you have tips to speed up this process?
public static void listFilesForFolder(final File folder,final File exported, int skipLine) {
try {
for (final File fileEntry : folder.listFiles()) {
String ext = fileEntry.getName().substring(fileEntry.getName().lastIndexOf('.') + 1);
System.out.println("-->> " + fileEntry.getName() + "-->>");
FileInputStream file = new FileInputStream(new File(fileEntry.getPath()));
if (fileEntry.isDirectory()) {
continue;
} else if(ext.equals("xlsx")) {
XSSFWorkbook myWorkBook = new XSSFWorkbook(file);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
Row row = rowIterator.next();
row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()){
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
default:
}
}
System.out.println("");
file.close();
}
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
I found the answer to my question.
You can not copy the whole row. You need to loop and read cell by cell.
The solution is:
Declare rowInrecmenter, colIncremnter, xssfWorkbook = new XSSFWorkbook();,
XSSFSheet createdSheet = xssfWorkbook.createSheet("Put any name here");
The variables above need to be outside the loop.
The rest of the codes are:
XSSFRow rowCreated = createdSheet.createRow((short)incr);
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
rowCreated.createCell(col).setCellValue(cell.getStringCellValue());
col++;
break;
case NUMERIC:
rowCreated.createCell(col).setCellValue(cell.getNumericCellValue());
col++;
break;
default:
}
}
xssfWorkbook.write(fileOut);
incr++;
col = 0;
workbook.close();
file.close();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}finally {
fileOut.close();
xssfWorkbook.close();
}

How to open xlsx files stored in a folder one by one and copy data to another file using JAVA

I wants to open xlsx files stored in a folder (one by one) and copy that sheet data column by column (if column name matches) to another file stored in other folder.
Column name mapping data is stored in a sheet.
Suppose sheet 1 contains column name mapping. using this mapping, I want to copy data of each column from each sheet stored in a particular folder to another file stored in another folder.
I tried with this code given below, but I am able to read and write compare headers, but I am unable to read from file one by one.
Code:
public class Read {
public static void main(String[] args) throws IOException{
//Create blank workbook
HSSFWorkbook workbook1 = new HSSFWorkbook();
HSSFSheet spreadsheet = workbook1.createSheet(" Info ");
//Create row object
// HSSFRow row1;
ArrayList<String> lst = new ArrayList<String>();
Read read = new Read();
String x ="Name";
//int columnIndex = 0;
lst = read.extractExcelContentByColumnIndex(x);
//int rowid = 0;
//row1 = spreadsheet.createRow(rowid++);
//Object [] objectArr = empinfo.get(key);
//int cellid = 0;
//int i=0;
for(int RowNum=0; RowNum<lst.size();RowNum++){
HSSFRow row1 = spreadsheet.createRow(RowNum);
for(int ColNum=0; ColNum<1;ColNum++){
HSSFCell cell = row1.createCell(ColNum);
cell.setCellValue(lst.get(RowNum).toString());
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("Writesheet.xls"));
// System.out.println(lst);
workbook1.write(out);
out.close();
}
public ArrayList<String> extractExcelContentByColumnIndex( String colName)
{
ArrayList<String> columndata = null;
int columnIndex= 0;
int flag=0;
try {
File f = new File("abc.xlsx");
FileInputStream ios = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(ios);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
columndata = new ArrayList<String>();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell1 = cellIterator.next();
String temp=cell1.getStringCellValue().toString();
//System.out.println(temp);
if(temp.equals(colName)){
columnIndex=cell1.getColumnIndex();
flag=1;
break;
}
}
if(flag==1)
{
flag = 0;
break;
}
}
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// System.out.println(row.getRowNum());
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(row.getRowNum() > 0){
//To filter column headings
if(cell.getColumnIndex() == columnIndex){
// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
columndata.add(cell.getNumericCellValue()+"");
break;
case Cell.CELL_TYPE_STRING:
columndata.add(cell.getStringCellValue());
break;
}
}
}
}
}
ios.close();
System.out.println(colName);
for(String ele : columndata){
System.out.println(ele);
}
} catch (Exception e) {
e.printStackTrace();
}
return columndata;
}
}
For reading files one by one you can use java.io.File.listFiles() method.
The method returns the array of abstract pathnames defining the
files in the directory denoted by this abstract pathname.
Sample code
File folder = new File(path / up / to / folder);
File[] listOfFiles = folder.listFiles();
for (File file: listOfFiles) {
if (file.isFile() && file.getName().contains(".xlsx")) {
// if you want to read only xlsx files
// Your logic
}
}

Iteration error in Excel sheet

When I tried to select items from the item list using Excel sheet through Java environment, only the first item is selected and executed. The next set of iteration is not happening.
int i=1;
while (i<=sheet.getLastRowNum() )
{
row = sheet.getRow(i);
String w = row.getCell(0).getStringCellValue();
// Processing : logic on "items" from excel
i++;
}
OK then try this sample firstly before your code. Check every column and row is visited. Maybe better way is using Iterators.
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Covert XLSX row into string and add to array

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

Passing a list of servlet values

Using apache poi, I am reading the first row values of an excel file like this
try
{
FileInputStream file = new FileInputStream(uploadedFile);
XSSFWorkbook workbook = new XSSFWorkbook(file);
for (int i =0; i < workbook.getNumberOfSheets(); i++)
{
XSSFSheet sheet = workbook.getSheetAt(i);
Iterator<Row> rowIterator = sheet.iterator();
String SheetName = "<span class='blue'><b>" +sheet.getSheetName()+ "<b></span><br>";
request.setAttribute("SheetName", SheetName);
Row row = rowIterator.next();
if(row.getRowNum() == 0)
{
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell1 = cellIterator.next();
switch(cell1.getCellType())
{
case Cell.CELL_TYPE_STRING:
String strval = cell1.getStringCellValue();
request.setAttribute("Values2", strval);
break;
}
}
}
}
file.close();
}catch(NoSuchElementException e)
{}
Now, I want to pass a list of values the strval is only sending one value, how do I sent many values??
How to send an array of items to my jsp page?
You can send List as an attribute value. For example:
List<String> cellValues = new ArrayList<String>();
while(cellIterator.hasNext())
{
Cell cell1 = cellIterator.next();
switch(cell1.getCellType())
{
case Cell.CELL_TYPE_STRING:
String strval = cell1.getStringCellValue();
cellValues.add(strval);
break;
}
}
}
}
request.settAttribute("Values2", cellValues);

Categories