reading an excel in java, variables are empty - java

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.

Related

After updating existing cell value in .xlsx file using POI, the file is giving HTTP 403 if used by an API

I have an excel file which contains many columns and one set of data row in it.
After changing the value of the asOf field, as I am using it in API which is taking excel file, gives 403 Forbidden error. I have checked the following things:
The field is updated correctly. (I checked the formatting and cell style of excel after updating it manually.)
If I change the cell value manually then API is giving 200.
Image For Failure Response: When asOf field updated by Java Code
Image For Pass Response: When asOf field updated manually.
The image of field which I am updating is below:
Below is the java code that I am using:
public static void excelFileReadAndUpdate() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("./src/test/resources/testdata/HoldingDataWeekendDate.xlsx"));
FileOutputStream fileOut = new FileOutputStream("./src/test/resources/testdata/HoldingDataWeekendDate.xlsx");
XSSFSheet sheet1 = wb.getSheetAt(0);
XSSFRow row = sheet1.getRow(1);
XSSFCell cell = row.getCell(0);
cell.setCellValue("2018-10-31");
wb.write(fileOut);
fileOut.close();
}
Note: I tried other approaches also like using the workbook and preserve the formatting but it is not working. If I update the field manually after opening the excel then it works.
Any suggestion/advice would be great help.
Thanks in advance.
After searching and applying many approaches, finally, it has been resolved by applying some code giving read/write permission to that folder/file in java.
public static void excelFileReadAndUpdate() throws IOException {
final File file = new File("location of your excel file directory");
file.setReadable(true, false);
file.setExecutable(true, false);
file.setWritable(true, false);
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("./src/test/resources/testdata/HoldingDataWeekendDate.xlsx"));
FileOutputStream fileOut = new FileOutputStream("./src/test/resources/testdata/HoldingDataWeekendDate.xlsx");
XSSFSheet sheet1 = wb.getSheetAt(0);
XSSFRow row = sheet1.getRow(1);
XSSFCell cell = row.getCell(0);
cell.setCellValue("2018-10-31");
wb.write(fileOut);
fileOut.close();
}

The process cannot access the file because it is being used by another process

I am trying to read data from one sheet of excel file and write to other sheet of same excel file.I have tried this :
FileInputStream file = new FileInputStream(new File("E:\\excel\\input.xlsx"));
//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();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print((int)cell.getNumericCellValue()+ " ");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue());
break;
}
}
System.out.println("");
}
file.close();
CreationHelper createHelper = workbook.getCreationHelper();
XSSFSheet newSheet = workbook.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = newSheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
System.out.println("writing to file");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(new File("E:\\excel\\input.xlsx"));
workbook.write(fileOut);
fileOut.close();
I have successfully read data from excel sheet But I am getting exception while writing in new sheet given below
java.io.FileNotFoundException: E:\excel\input.xlsx (The process cannot access the file because it is being used by another process)
This will happen when you are trying to execute this program while the "input.xlsx" file is already opened by another application.
Please close any instance of MS Excel and try to run it again
Just a guess but XSSFWorkbook should be implementing Closeable thus it has a .close() that should be called.
Maybe the file result still in use because of that?
You are probably going to need a middle step there: write to a new file, close the XSSFWorkbook and then copy the new file on the old one that you want to write on

adding cells in excel with java apache

I am reading an already existing excel file and trying to add certain cells for example(C4-C15). I am having difficult manipulating the files through java. I am using apache poi, and would appreciate any help or direction.
In order to access a cell in Apache POI, you have to get a row first, and then get cell within chosen row. Below is example:
//Input file
InputStream inp = new FileInputStream("workbook.xls");
//Create workbook instance
Workbook wb = WorkbookFactory.create(inp);
//Create sheet instance
Sheet sheet = wb.getSheetAt(0);
for(int i = 3; i <= 16; ++i){ //Rows from 4 to 15 (Apache POI is zero based)
Row row = sheet.getRow(i);
Cell cell = row.getCell(2); //Column "C"
//Do something with cell
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
Source (more examples here)

Append Excel file using Apache POI

I have a java program that prints 1000 integer values each I run it. I want to copy the output to an excel file each time I run the program. I want to output the first run in the first column in excel file and then copy the next runs in the subsequent columns in the same excel file. For example:
Run: 1
value1
value2
.
.
value1000
Run:2
value1
value2
.
.
value1000
I want the first output in the first column of an excel file and the second output in the second column
Here is my code:
int rownum=1;
int cellnum=1;
File file;
HSSFWorkbook workbook;
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
public void writeOutput(double meandispersion) {
String dispersion = Double.toString(meandispersion);
HSSFRow row = sheet.createRow(rownum++);
HSSFCell cell = row.createCell(cellnum);
cell.setCellValue("dispersion");
try {
FileOutputStream out = new FileOutputStream("newFile.xls");
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
There are a total of 1000 time steps in the main code and in each time step this method is called and the value of meandispersion is passed to it. It prints the 1000 values in 1000 rows in the first column. The problem is that when I run the program second time I want to copy the 1000 values in the second column, for third run 3rd column and so on. Currently it is not appending the values, it overwrites the entire file. Can anyone point out the problem?
You have to read the existing file, append your new output to the existing data yourself (in correct column and then write it to the file.
Right now you are not reading the file at all, which would overwrite the existing contents.
Hope this helps.
POI's Quick Guide aka the "Busy Developers' Guide to HSSF and XSSF Features" contains lots of code snippets, including one that talks about opening an existing workbook, and reading and writing and saving the modified workbook (example verbatim copied from that page, added some comments):
InputStream inp = new FileInputStream("workbook.xls");
// notice how the Workbook must be constructed from the existing file
Workbook wb = WorkbookFactory.create(inp);
// Navigating in POI always follows the same logic:
// 1. grab a sheet
// 2. grab a row from that sheet
// 3. grab a cell from that row
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
// a condition like the one that follows will be needed to know in what column
// you have to write your data:
if (cell == null)
cell = row.createCell(3);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("a test");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
That, and the other examples on that page should get you up to speed quickly.

How to go though the sheets of a Workbook with Apache POI?

I am a real newb programer trying to make a small java program that edits spreadsheets for a friend using Apache Poi. Currently I go through the excel file using this code:
Sheet paxgs = rs1.getSheetAt(0);
for (Row row : paxgs) {
Cell secCell = row.getCell(1);
Cell firstCell = row.getCell(0);
if (firstCell!=null && firstCell.getCellType()==firstCell.CELL_TYPE_STRING)
}
The problem is that I don't know the exact number of sheets that the excel file is going to have. I tried :
Workbook rs1 = WorkbookFactory.create(new FileInputStream(filename));
for (Sheet sheet : rs1)
but it didn't work so I was wondering if there is any way to go through all the sheet of a workbook.
A Workbook doesn't implement Iterable<Sheet> like a Sheet implements Iterable<Row>, so you can't use an "enhanced" for loop. But you can loop through the Sheet objects yourself, with a traditional for loop. Use getNumberOfSheets() to find the number of sheets, and getSheetAt to retrieve the individual Sheet objects.
for (int i = 0; i < workbook.getNumberOfSheets(); i++)
{
Sheet sheet = workbook.getSheetAt(i);
// Process your sheet here.
}
The workbook contains a protected field "_sheets" which is of type java.util.List
so:-
rs1._sheets.size();
Should get you the number of sheets. You should also be able to iterate through this list.

Categories

Resources