Why does not load infomation from excel (*.xlsx) (use Apache POI)? - java

Try to load information on JSP from Excel file (*.xlsx) use Apache POI 3.15.
View information in excel
num solution
1 First
2 Second
3 Third
try to use code
try {
InputStream ExcelFileToRead = new FileInputStream("C:\\server\\to_db.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) {
out.print(cell.getStringCellValue() + " ");
} else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
out.print(cell.getNumericCellValue() + " ");
} else {
//U Can Handel Boolean, Formula, Errors
}
}
out.println("Succefully!!!");
}
}
catch (Exception e) {
out.println( "exception: "+e);
}
Getting a strange result:
absent error and absent information on JSP....
Problem problem is reproduced in all browsers.
If I try open C:\server\to_db.xlsx OS Windows responce "File is busy".
What could be the problem and how to solve it?

When you open a FileInputStream or FileOutputStream, you need to close it otherwise your file could be locked by the process according to the OS used especially on Windows OS. More generally speaking, you need to close all Closeable objects that you use to prevent any leaks or issues like this one.
So you should rewrite your code as next to use the try-with-resources statement that will automatically close the resources for you.
try (InputStream ExcelFileToRead = new FileInputStream("C:\\server\\to_db.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead)) {
...
Indeed in your code you have 2 Closeable objects which are ExcelFileToRead and wb.

I think you have to close the file using ".close() ". This may help you.

In lib directory absent some commons libs
commons-collections4-4.1.jar, commons-codec-1.10.jar, commons-fileupload-1.3.jar
their presence solved problem.

Related

zip file instead of an excel file when using XSSFWorkbook in java how do I open this

I am trying to write an excel file using java. I'm looking for just simply a column with one username per row right now, and then will build upon this later once I understand what is going a bit better. I get a zip file instead of the expected excel file, and it contains docProps, _rels, xl, and [Content_Types].xml. I don't understand how to open this zip file as though it is an excel file. I have not had luck finding the answer as all the tutorials I see show it to be a straight forward excel file, not a zip file. Is it a configuration I'm missing or is it to do with linux?
Here's my code, and what I end up with:
private void createExcelSheet(Assignment assignment) throws FileNotFoundException {
String excelFilePath = Configuration.DIRECTORY_ROOT+"/tests/"+assignment.getAssn_number()+"/gradebook-"+assignment.getAssn_number();
int rowNum = 0;
int col = 0;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(assignment.getAssn_number()+" Grades ");
XSSFRow row = spreadsheet.createRow(rowNum);
Cell cell;
for (User user : userService.getUsers() ) {
row = spreadsheet.createRow(rowNum);
cell = row.createCell(rowNum);
cell.setCellValue(user.getStudent_id());
rowNum++;
}
try (FileOutputStream fos = new FileOutputStream(excelFilePath)) {
workbook.write(fos);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

Updating value of cells in Excel with Java Apache POI

I am trying to update an existing Excel with Apache POI.
The thing is, I have an excel having in its 3rd column telephone numbers, and I want to correct them to the specific format using if-statements.
But I cannot write to the file.
Here is the code I am using:
public void readingExcel(String fileName) throws Exception {
try (FileInputStream file = new FileInputStream(new File(fileName))) {
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
int counter = 0;
for (Row row : sheet) {
int columnIndex = 2;
row = CellUtil.getRow(counter, sheet);
Cell cell = CellUtil.getCell(row, columnIndex);
if (formatter.formatCellValue(cell).length() == 8)
cell.setCellValue("+216" + formatter.formatCellValue(cell));
if (formatter.formatCellValue(cell).length() == 11 && formatter.formatCellValue(cell).startsWith("216"))
cell.setCellValue("+" + formatter.formatCellValue(cell));
counter++;
}
FileOutputStream outFile =new FileOutputStream(new File(fileName));
workbook.write(outFile);
outFile.close();
}
}
And I am getting this error
org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x0000000000000000, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:181)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:140)
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.<init>(NPOIFSFileSystem.java:302)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:398)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:379)
at excelapp.myClass.readingExcel(myClass.java:50)
at excelapp.myClass.<init>(myClass.java:41)
at excelapp.ExcelApp.main(ExcelApp.java:26)
The thing is that it is really important for today, and I am getting really stuck on updating the values of that column :-/ anyone has an idea? I think I'm writing the wrong way..

How to resolve the java.lang.VerifyError: org/apache/poi/xssf/usermodel/XSSFWorkbook?

I'm trying to read the xlsx file from asset folder. I received below exception,
05-16 10:12:05.613: E/AndroidRuntime(2915): FATAL EXCEPTION: main
05-16 10:12:05.613: E/AndroidRuntime(2915): java.lang.VerifyError: org/apache/poi/xssf/usermodel/XSSFWorkbook
before this exception, I received some warnings also like,
Could not find method
org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument$Factory.parse,
referenced from method
org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead
VFY: unable to resolve exception class 3612
(Lorg/apache/xmlbeans/XmlException;)
I have added poi 3.12 library on my application, libraries screenshot as below,
And I have checked poi-3.12 and poi-ooxml-3.12 jar files in Order and Export, screenshot as below,
I used below code,
InputStream is = context.getAssets().open("sample.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(is);
XSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = sheet.getRow(0).getCell(0);
String value = cell.getStringCellValue() + "";
I want to read and write the .XLSX and .XLS files. How to resolve this issue?
Thanks in Advance.
Firs you should connect to your project these jars.
Then use this code for reading
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
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
Updated your code to able to read and write the .XLSX and .XLS files
InputStream is = context.getAssets().open("sample.xlsx"));
Workbook workbook = WorkbookFactory.create(is);
Sheet sheet = workbook.getSheetAt(0);
Cell cell = sheet.getRow(0).getCell(0);
String value = cell.getStringCellValue() + "";
For your libraries, please have a look here android getting java lang verify error when using external java lib

reading an excel in java, variables are empty

I try to read this excel file: Test.xlsx, to do this I used an example I found on the internet, but
I used this link as en example: http://howtodoinjava.com/2013/06/19/readingwriting-excel-files-in-java-poi-tutorial/
it doens't work.
I copied the url for the file, so there is no error there.
Whenever I run it, it doensnt show errors just : []
When I debug it, it shows me that the listsize = 0
What should I change?
ArrayList<String> list = new ArrayList<String>();
#Override
public List<String> getExcel(){
try {
FileInputStream file = new FileInputStream(new File("C:\\Users\\user\\Documents\\Test.xlsx"));
//Create Workbook instance holding reference to .xlsx file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first/desired sheet from the workbook
HSSFSheet sheet = workbook.getSheet("Sheet1");
//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
if (row.getRowNum() <= 7) {
continue;// skip to read the first 7 row of file
}
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
list.add(cell.getStringCellValue());
}
//System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
You are using the wrong class for the file you are trying to open (Test.xlsx). By the extension, I can assume this is an Excel 2007 or later document. Use HSSFWorkbook for Excel 2003 and XSSFWorkbook for Excel 2007 or later. Review Apache POI documentation that came with the downloaded package. It contains basic tutorials on how to accomplish this.
You will need to replace all of the 'HSSF' classes for the 'XSSF' equivalent. Beware that the methods called to create the parts of the document (i.e. Workbook, Sheet, etc) are not always the same.
Try this link. I created a small demo for a simple tutorial on Apache POI some time back. There is an Excel example you could follow. The location contains source code and a set of slides that you should be able to follow easily.

Delete multiple Rows containing a specific String

I've been trying to develop a code that can delete multiple rows containing a specific String "POST". I have been doing this like:
private void processExcelFile(File f_path){
File path=f_path;
HSSFWorkbook wb = null;
try{
FileInputStream is=new FileInputStream(path);
wb= new HSSFWorkbook(is);
HSSFSheet sheet = wb.getSheetAt(0);
int j = 0;
for(Row row: sheet){
for(Cell cell : row){
count++;
if (cell.getCellType() == Cell.CELL_TYPE_STRING){
if (cell.getRichStringCellValue().getString().trim().contains("POST")){
rowcount_post=row.getRowNum();
System.out.print("ROW COUNT= "+rowcount_post);
HSSFRow removingRow = sheet.getRow(rowcount_post);
if (removingRow != null) {
sheet.removeRow(removingRow);
}
}
}
}
}
} catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
try{
FileOutputStream fileOut = new FileOutputStream("C:/juni.xls");
wb.write(fileOut);
} catch(Exception e) {
JOptionPane.showMessageDialog(this,e.getMessage(),"SAVE Error",JOptionPane.ERROR_MESSAGE);
}
}
It is a matter of fact that it only deletes one row at a time. Is it possible that I could delete all the rows containing the String POST?
Why do you have a problem with deleting them one at a time? It doesn't seem too inefficient...
Anyway, I'm pretty sure you still have to loop over every cell to see if it contains "POST".
If you have a problem specifically with deleting one row at a time, you could save the indices of the rows you want to delete in an array; then use the array to delete the saved rows.
The reason you're deleting them one at a time is because you're finding them one at a time. As the other poster mentioned, you could keep track of the locations through out your program (whether that be during this loop), but that wouldn't make it algorithmically efficient (unless you kept track of it somewhere else and pass that info to this method).
I'm not too familiar with using Excel files in Java, but these seems to be a solid way to do it.

Categories

Resources