I'm trying to open all the files that are linked in an Excel Sheet using Apache POI. This is what I've got:
FileInputStream inputstream = new FileInputStream(file);
workbook = new HSSFWorkbook(inputstream);
HSSFSheet sheet = workbook.getSheetAt(0);
log("Processing Sheet: " + sheet.getSheetName());
Iterator rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
HSSFRow row = (HSSFRow) rowIterator.next();
Iterator cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
HSSFCell cell = (HSSFCell) cellIterator.next();
if(cell.getHyperlink() != null){
HSSFHyperlink hyperlink = cell.getHyperlink();
log("Hyperlink found: " + hyperlink.getAddress());
try{
FileInputStream fs = new FileInputStream(hyperlink.getAddress());
}catch(Exception ex){
log(ex.getMessage());
}
}
}
}
But hyperlink.getAddress() doesn't return the correct path, it looks like it returns the relative path but without ../.
I also tried using the getDirectoryRoot() method on the workbook. But that just returns /. I have the path to my Excel file but without the base path that the excel uses or the ../'s in the attachments path, I'm not able to get the correct path.
Instead you can use one easier way: Take a file with that relative address and then get the absolute path of that file.
e.g.
System.out.println(new File(hyperlink.getAddress()).getAbsolutePath());
Related
I am using NetBeans 14 to build a Java 8 project with Ant build. I have included:
poi-5.2.3.jar
poi-ooxml-full-5.2.3.jar
SpareseBitSet-1.2.jar
commons-codec-1.15.jar
commons-collections4-4.4.jar
commons-compress-1.2.1.jar
commons-io-2.11.0.jar
commons-math3-3.6.1.jar
curvesapi-1.0.7.jar
xml-api-1.4.0.1.jar
xmlbeans-5.1.1.jar
It builds fine. When I create a Workbook using an xls file as input it works. When I try to create a Workbook using an xlsx file it throws an exception reporting:
IO Exception processing input Bio file
java.io.IOException: Your InputStream was neither an OLE2 stream, nor an OOXML stream or you haven't provide the poi-ooxml*.jar in the classpath/modulepath - FileMagic: OOXML, having providers: [org.apache.poi.hssf.usermodel.HSSFWorkbookFactory#71a2f010]
at org.apache.poi.ss.usermodel.WorkbookFactory.wp(WorkbookFactory.java:334) ~[poi-5.2.3.jar:5.2.3]
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:311) ~[poi-5.2.3.jar:5.2.3]
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:277) ~[poi-5.2.3.jar:5.2.3]
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:255) ~[poi-5.2.3.jar:5.2.3]
I've tried changing ooxml library types (-lite, -full, both, etc.).
Any help would be welcome.
I have tried sample code, working fine.
File myFile = new File("C://temp/Employee.xlsx"); 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()) {
// Enter you code here to fetch data based on cell type
}
} System.out.println("");
}
I'm trying to create a Java application that can read and clean an Excel file in .xlsx format (by comparing it to a master list, also in Excel format) before writing it to a new Excel file. I also need to be able to post the cleaned file to a web app, but that's for later.
I'm using Apache POI, and have been able to successfully read the Excel file (in the output section in Eclipse it doesn't start from the first row though).
Here's where I'm stuck. I've been able to read the rows using an iterator, but how do I extract all these values to variables? Can I create a data table?
public class ReadAndCleanExcel {
public void readExcel(String filePath) {
Object[][] data = null;
final DataFormatter df = new DataFormatter();
try {
FileInputStream file = new FileInputStream(new File(filePath));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
int rownum = 0;
int colnum = 0;
Row r=rowIterator.next();
int rowcount=sheet.getLastRowNum();
int colcount=r.getPhysicalNumberOfCells();
data = new Object[rowcount][colcount];
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
colnum = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
data[rownum][colnum] = df.formatCellValue(cell);
System.out.print(df.formatCellValue(cell).toUpperCase() + " ");
colnum++;
}
rownum++;
System.out.println();
}
file.close();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
So I have created a class that searches an excel file and prints all the rows and columns of the file. Now I have an exception file not found error. In order to fix this error I have changed the file path in the code but for some reason I get the same error and the error message in the console shows the previous file path I was using that gave me error.
I know the new file path is correct but Eclipse doesn't seem to recognize that the code has been updated. Here is the code from the class:
public class ExcelReader {
public static final String SAMPLE_XLSX_FILE_PATH = "K:\\Documents\\Project\\Netword_GUI\\Netword_GUI\\src\\libs\\cc2017.xlsx";
public static void main(String[] args) throws IOException, InvalidFormatException {
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
// Retrieving the number of sheets in the Workbook
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
/*
=============================================================
Iterating over all the sheets in the workbook (Multiple ways)
=============================================================
*/
// You can obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
//System.out.println(sheet.getRow(0));
System.out.println("=> " + sheet.getSheetName());
}
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// You can obtain a rowIterator and columnIterator and iterate over them
System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// Now let's iterate over the columns of the current row
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();
}
if (sheet.getActiveCell() == null) {
// Closing the workbook
workbook.close();
}
}
}
Now here is the error message displayed in the console:
Exception in thread "main" java.io.FileNotFoundException:
C:\Users\User\Dropbox\Placement\Private_Backup\Netword_GUI\Netword_GUI\src\cc2017.xlsx
at
org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:250)
at
org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:226)
at
org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:205)
at ExcelReader.main(ExcelReader.java:13)
Notice: The file path in the console is different to the file path in the code. Previously the file path in the error message was in the code this is because I have the same class on another computer so the file path was changed as the location is different on the computer I am currently working on.
Sometimes the build in Eclipse is not up to date.
In that case you should clean and re-build your project (from the "Project" menu)
could you please add your code to make every one get the big picture of your code to give you a correct answer
try this one
File f=new File(fixed_file_path);
Workbook workbook = WorkbookFactory.create(f);
I am trying to read a xlsx file with particular row number which will be provided as parameter.
I am getting NullPointerException if sheet.getRow(RowNum). I am able to read the xlsx file if i adjust column width and save it again manually. But that destroys my purpose of automation. I am able to read any other xlsx files which are created manually.
Here is the sample code :
public String readCouponCode(int getRowCount) {
try {
Registration reg=new Registration();
File inputFile = new File(this.DownloadFile);
System.out.println(DownloadFile);
// 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);
// Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
// Traversing over each row of XLSX file
Row row = sheet.getRow(getRowCount);
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int cellIndex = cell.getColumnIndex();
// System.out.println(cellIndex);
if (cellIndex == 0) {
CouponCode = cell.getStringCellValue();
System.out.println(cell.getStringCellValue() + "\t");
}
}
} catch (Exception e) {
System.err.println("Exception :" + e.getMessage());
}
return CouponCode;
}
I also tried with XSSFRow but it yields same result.
Note : I tried by commenting sheet.getRow() line and it prints only the last row. I tried to get number of rows by using sheet.getPhysicalNumberOfRows(), it gives 1 but actually my xlsx file has 7 rows.
Jars used:
dom4j poi-3.13-20150929
poi-excelant-3.13-20150929
poi-ooxml-3.13-20150929
poi-ooxml-schemas-3.13-20150929
xmlbeans-2.5.0
I am trying to read an xlsx file but I am getting the error "Work book can not be resolved a type". How to solve the same?
InputStream input = new BufferedInputStream(
new FileInputStream("F://myFile.xlsx"));
POIFSFileSystem fs = new POIFSFileSystem( input );
Workbook wb1 = WorkbookFactory.create(new File(fs)); // error is here
HSSFSheet sheet = wb.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while( rows.hasNext() ) {
HSSFRow row = (HSSFRow) rows.next();
System.out.println("\n");
Iterator cells = row.cellIterator();
Java cannot read Excel files directly. You need a third party library to accomplish this. From the given code, looks like you need to add the libraries from Apache POI, specifically POI-HSSF and POI-XSSF.
Firstly, you need to have all the appropriate Apache POI component jars and their dependencies on your classpath. Secondly, you then need to import the POI classes.
Once you've downloaded Apache POI, and added the components to your classpath, your code would then look something like:
import org.apache.poi.ss.usermodel.*;
public class POIExample {
public static void main(String[] args) {
File f = new File("F://myFile.xlsx"));
Workbook wb1 = WorkbookFactory.create(f);
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
System.out.println("\n");
for (Cell cell : row) {
System.out.println("Found Cell");
}
}
}
}