Java Read Excel File via FileDialog - java

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

Related

How to get cell value from the cell which consists of formula in excel xls file

I am writing java code to read excel file and to create an object from that but one column consists of formula when I read cell formula is coming in value field instead of value
I tried to get from cell index
I tried to get value from iterator(hasnext()) method :
like:
public static void CheckDuplicate(File file) throws Exception {
Set newReordsList = new LinkedHashSet();
LinkedHashMap<String, DataCleansingObject> lhm = new LinkedHashMap<String, DataCleansingObject>();
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
HSSFRow row;
Iterator< Row> rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
row = (HSSFRow) rowIterator.next();
if(row.getRowNum() == 0) {
continue;
}
DataCleansingObject dataObj = new DataCleansingObject();
Iterator< Cell> cellIterator = row.cellIterator();
String key = "";
if (cellIterator.hasNext()) {
dataObj.setDocType(row.getCell(1).toString());
dataObj.setDocNo(row.getCell(2).toString());
dataObj.setDocVer(Long.parseLong(row.getCell(3).toString()));
dataObj.setDocPart(row.getCell(4).toString());
dataObj.setDocLang(row.getCell(5).toString());
dataObj.setDocRev(row.getCell(6).toString());
dataObj.setDocStatus(row.getCell(7).toString());
dataObj.setDocSD(row.getCell(8).toString());
dataObj.setDocLD(row.getCell(9).toString());
dataObj.setDocChangeNumber(row.getCell(10).toString());
key = row.getCell(1).toString() + "_" + row.getCell(2).toString() + "_" + row.getCell(3).toString() + "_" + row.getCell(4).toString();
}
lhm.put(key, dataObj);
}
fis.close();
copyInExcel(newReordsList);
}
When ever I call below line
Long.parseLong(row.getCell(3).toString())
I need to get long value not formula in that cell

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.

Read or Fetch all the column headers in a excel sheet

I wanted to just read all the column headers of my excel sheet.
public class Reader_2 {
public static final String SAMPLE_XLSX_FILE_PATH = "C:/Users/kqxk171/Documents/Records Management
Application/9.2_initial_test_report.xlsx";
public static void main(String[] args) throws IOException {
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
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());
}
Sheet sheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
for (Row row: sheet) {
for(Cell cell: row)
{
row.getRowNum();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
System.out.println();
}
}
}

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

Apache POI XSSF reading in excel files

I just have a quick question about how to read in an xlsx file using the XSSF format from Apache.
Right now my code looks like this:
InputStream fs = new FileInputStream(filename); // (1)
XSSFWorkbook wb = new XSSFWorkbook(fs); // (2)
XSSFSheet sheet = wb.getSheetAt(0); // (3)
...with all the relevant things imported. My problem is that when I hit run, it gets stuck at line (2), in almost an infinite loop. filename is just a string.
If anybody could give me some sample code on how to fix this I would really appreciate it. All i want right now is to read in a single cell from an xlsx file; I was using HSSF for xls files and had no problems.
Thanks for your help,
Andrew
I bealive that this will answer your questions: http://poi.apache.org/spreadsheet/quick-guide.html#ReadWriteWorkbook
In short, your code should look like this:
InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
InputStream inp = null;
try {
inp = new FileInputStream("E:/sample_poi.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Header header = sheet.getHeader();
int rowsCount = sheet.getLastRowNum();
System.out.println("Total Number of Rows: " + (rowsCount + 1));
for (int i = 0; i <= rowsCount; i++) {
Row row = sheet.getRow(i);
int colCounts = row.getLastCellNum();
System.out.println("Total Number of Cols: " + colCounts);
for (int j = 0; j < colCounts; j++) {
Cell cell = row.getCell(j);
System.out.println("[" + i + "," + j + "]=" + cell.getStringCellValue());
}
}
} catch (Exception ex) {
java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
inp.close();
} catch (IOException ex) {
java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
}
}
Why are you breaking the file into an InputStream? XSSFWorkbook has a constructor that simply takes the path as a String. Just hard code the path of the string in. Once you create the workbook you can create XSSFSheets from that. Then XSSFCells, which will then finally allow you to read the contents of a single cell (cells are based on x,y locations, essentially)
You can try the following.
private static void readXLSX(String path) throws IOException {
File myFile = new File(path);
FileInputStream fis = new FileInputStream(myFile);
// Finds the workbook instance for XLSX file
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
// Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = mySheet.iterator();
// Traversing over each row of XLSX file
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_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default :
}
}
System.out.println("");
}
}
this works fine: try it
File filename = new File("E:/Test.xlsx");
FileInputStream isr= new FileInputStream(filename);
Workbook book1 = new XSSFWorkbook(isr);
Sheet sheet = book1.getSheetAt(0);
Iterator<Row> rowItr = sheet.rowIterator();
public class ExcelReader{
public String path;
public static FileInputStream fis;
public ExcelReader(){
System.out.println("hello");
}
public ExcelReader(String path){
this.path=path;
fis=new FileInputStream(path);
XSSFWorkbook workbook=new XSSFWorkbook(fis);
XSSFSheet sheet=workbook.getSheet("Sheet1");//name of the sheet
System.out.println(sheet.getSheetName());
System.out.println(sheet.getLastRowNum());
System.out.println(sheet.getRow(2).getCell(3));
}
public static void main(String[] args) throws IOException {
ExcelReader excel=new ExcelReader("path of xlsx");
}
}
I have the same error, I have just updated the pom dependencies with the same version. It worked.
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
// Load sheet- Here we are loading first sheet only
XSSFSheet xlSheet = wb.getSheetAt(0);
Here code recognizing only first sheet - In my Excel multiple sheets are there so facing problem to change sheet2 to sheet1(getSheetAt(0))...

Categories