Covert XLSX row into string and add to array - java

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

Related

Converting issue in java - xlsx to csv problem

I am currently working on a small program to automatically convert xlsx files to csv, but it does not really work.
It has an input file and an output file, the details are in the codesnippet.
You need the followings:
import java.io.*;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
Can you please help me fix it? Thanks
static void convertToXlsx(File inputFile, File outputFile) {
// For storing data into CSV files
StringBuffer cellValue = new StringBuffer();
try {
FileOutputStream fos = new FileOutputStream(outputFile);
// Get the workbook instance for XLSX file
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wb.getSheetAt(0);
Row row;
Cell cell;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
cellValue.append(cell.getBooleanCellValue() + ",");
break;
case Cell.CELL_TYPE_NUMERIC:
cellValue.append(cell.getNumericCellValue() + ",");
break;
case Cell.CELL_TYPE_STRING:
cellValue.append(cell.getStringCellValue() + ",");
break;
case Cell.CELL_TYPE_BLANK:
cellValue.append("" + ",");
break;
default:
cellValue.append(cell + ",");
}
}
}
fos.write(cellValue.toString().getBytes());
fos.close();
} catch (Exception e) {
System.err.println("Exception :" + e.getMessage());
}
}
static void convertToXls(File inputFile, File outputFile) {
StringBuffer cellDData = new StringBuffer();
try {
FileOutputStream fos = new FileOutputStream(outputFile);
// Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell;
Row row;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
cellDData.append(cell.getBooleanCellValue() + ",");
break;
case Cell.CELL_TYPE_NUMERIC:
cellDData.append(cell.getNumericCellValue() + ",");
break;
case Cell.CELL_TYPE_STRING:
cellDData.append(cell.getStringCellValue() + ",");
break;
case Cell.CELL_TYPE_BLANK:
cellDData.append("" + ",");
break;
default:
cellDData.append(cell + ",");
}
}
}
fos.write(cellDData.toString().getBytes());
fos.close();
} catch (FileNotFoundException e) {
System.err.println("Exception" + e.getMessage());
} catch (IOException e) {
System.err.println("Exception" + e.getMessage());
}
}
public static void main(String[] args) {
File inputFile = new File("C:\input.xls");
File outputFile = new File("C:\output1.csv");
File inputFile2 = new File("C:\\Users\\lendvaigy\\Desktop\\AKK\\DOWNLOAD TEST\\legjobb-eladasi-es-veteli-hozamok-arfolyamok.xlsx");
File outputFile2 = new File("C:\\Users\\lendvaigy\\Desktop\\AKK\\DOWNLOAD TEST\\legjobb-eladasi-es-veteli-hozamok-arfolyamok.csv");
convertToXls(inputFile, outputFile);
convertToXlsx(inputFile2, outputFile2);
}
The main problem is that I am not a professional one, just a DIY rookie trying to create small programs.
The problem in your code is in convertToXls(). For converting xls to csv file use XSSFWorkbook instead of HSSFWorkbook.
Try changing following in convertToXls().
static void convertToXls(File inputFile, File outputFile) throws IOException {
Workbook wb = new XSSFWorkbook(inputFile.getPath());
DataFormatter formatter = new DataFormatter();
PrintStream out = new PrintStream(new FileOutputStream(outputFile), true, "UTF-8");
Sheet sheet =wb.getSheetAt(0);
for (Row row : sheet) {
boolean firstCell = true;
for (Cell cell : row) {
if (!firstCell)
out.print(',');
String text = formatter.formatCellValue(cell);
out.print(text);
firstCell = false;
}
out.println();
}
}
And rest should work as it is.

Java Read Excel File via FileDialog

I get an IOException with the code below. Whats the problem?
What I want is to Read an Excel File xlsm and xls or xlsx via the filedialog after the import read the excel and work with it.
public class start {
public static void main(String[] args) throws IOException, InvalidFormatException {
JFrame yourJFrame = new JFrame();
FileDialog fd = new FileDialog(yourJFrame, "Choose a file", FileDialog.LOAD);
fd.setVisible(true);
String filename = fd.getFile();
String filepth = fd.getDirectory();
Workbook workbook = WorkbookFactory.create(new File(filepth + filename));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
System.out.println("=> " + sheet.getSheetName());
}
String
DataFormatter dataFormatter = new DataFormatter();
System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
System.out.println();
}
workbook.close();
}
}

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

java excel read one column

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

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