Adding data to excel file using apache POI - java

I gotta add info to a already existing excel file. The reader I built works wonderfully,but every tutorial I've seen just shows how to edit an already existing file or creating a new one. I just need to add 4 cells with info at the end of the file (if the existing file has 2 rows of data I'll add the new data in the third row), and every time it kicks me with an error when trying to access the file, and I'm using the same method to access the file in the reader, and that one works, it doesn't make sense.Here's the code so far:
try{
FileInputStream Album=new FileInputStream(new File("songs.xls"));
HSSFWorkbook workbook=new HSSFWorkbook(Album);
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
int last=sheet.getLastRowNum();
Row row =sheet.createRow(last+1);
Cell cell1=row.createCell(0);
cell1.setCellValue(name);
Cell cell2=row.createCell(1);
cell2.setCellValue(artist);
Cell cell3=row.createCell(2);
cell3.setCellValue(duration);
Cell cell4=row.createCell(3);
cell4.setCellValue(genre);
try {
FileOutputStream out=new FileOutputStream(new File("c:/Users/twhit/Documents/U/2016/1ro 2016/POO/IntelliJ/Proyecto1POO/src/Canciones.xls"));
workbook.write(out);
out.close();
}
catch (Exception e){
e.printStackTrace();
}
}
catch(Exception e){
e.printStackTrace();
}

Related

Java Writing Data to Excel - WorkbookFactory

I am trying to add some data to, already existing file which I created with; copyFileNIO(fromFile, toFile) method. To add data to already existing file I am using this code block:
try {
copyFileNIO(fromFile, toFile);
System.out.println("Copy file is done.");
// Creating file object of existing excel file
File xlsxFile = new File(toFile);
System.out.println("ok");
// Creating input stream
InputStream inputStream = new FileInputStream(xlsxFile);
System.out.println("okkk");
// Creating workbook from input stream
Workbook wb = WorkbookFactory.create(inputStream);
System.out.println("okkkk");
// Reading first sheet of excel file
Sheet sheet = wb.getSheetAt(0);
// Getting age cell of first row from the sheet
Cell cell = sheet.getRow(1).getCell(3);
// Updating the cell value with new data
cell.setCellValue(30);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Copy file is done.");
}
However, Workbook is giving error, I tried also XSSF its not working. I do not know what causes this. You can see ambda$7 exception:
at application.Sbt.lambda$7(Sbt.java:492) -> which leads Workbook wb = WorkbookFactory.create(inputStream);
I added some System.out.println as can seen on code: output of these methods are
Copy file is done.
ok
okkk
Exception ...
How can i solve this problem ? Thank you
I confirmed my file exists and patch is correct. Changed inputstream and workbook to -> Workbook wb = WorkbookFactory.create(new File(toFile)); Still same error
full error message and stack trace
at org.apache.poi.poifs.filesystem.FileMagic.valueOf(FileMagic.java:177)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:309)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:277)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:255)
at application.Sbt.lambda$7(Sbt.java:491)
Apache POI -> 5.2.3

How can I load CSV file into Excel sheet using Java

I have an Excel spreadsheet that has the first sheet designated for the raw data. There are 3 more sheets that are coded to transform and format the data from the raw sheet. The fifth sheet has the final output.
How can I use Java:
load the data from the CSV file into the first sheet of the excel file?
save the data from the 5th sheet into the new CSV file.
Also, if the original CSV has thousands of rows, I assume the multi-sheet transformations would take some time before the 5th sheet gets all the final data - is there a way to know?
I would follow this approach:
Load the specific .csv file and prepare to read it with Java
Load the .xlsx file and change it according to your requirements and the data that you get from the .csv file. A small example of how an excel file is changed with Apache POI can be seen below:
try
{
HashMap<Integer, ArrayList<String>> fileData; // This for example keeps the data from the csv in this form ( 0 -> [ "Column1", "Column2" ]...)
// Working with the excel file now
FileInputStream file = new FileInputStream("Data.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(file); // getting the Workbook
XSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
AtomicInteger row = new AtomicInteger(0);
fileData.forEach((key, csvRow) ->
{
//Update the value of the cell
//Retrieve the row and check for null
HSSFRow sheetRow = sheet.getRow(row);
if(sheetRow == null)
{
sheetRow = sheet.createRow(row);
}
for (int i = 0; i < csvRow.size(); i++)
{
//Update the value of cell
cell = sheetRow.getCell(i);
if(cell == null){
cell = sheetRow.createCell(i);
}
cell.setCellValue(csvRow.get(i));
}
});
file.close();
FileOutputStream outFile =new FileOutputStream(new File("Data.xlsx"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
After saving the .xlsx file, you can create the .csv file by following this question.

xlsx file created with apache poi cannot be opened

I am using Apache POI 3.17 to create xlsx files and filling it with data from the db. The file gets created fine but when I try to open it, I get 'incompatible format' error even though when I inspect the file, I can see that it is a Microsoft spreadsheet file. I looked at here,here and here and tried all these examples but didn't help and I don't know where the problem is. Here is my file creation code:
File excelFile = new File("C:\\myFile.xlsx"); //a new file to be created
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(rowIndex);
Cell cell;
//some font and style creation
for(String eachHeader : headers) {
cell = row.createCell(cellIndex);
cell.setCellValue(eachHeader);
cell.setCellStyle(headerStyle);
cellIndex++;
}
//some more row and cell creation
try {
//finally try to write all this content into the excel file
OutputStream out = new FileOutputStream(excelFile);
workbook.write(out);
out.close();
logger.debug("Worksheet created: " + excelFile.getAbsolutePath());
}catch(Exception exc) {
logger.error("Error occured while creating or writing to the excel file: " + exc.getMessage());
}
Again, the file is created fine with some data in it as I can see that the size is not 0, but just cannot open it, why??

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.

append data into xlsx file through java

I am using Apache POI for writing into .xlsx file. I can write into .xlsx file but I am unable to append new content. How can I append new content in the .xlsx file?
My Code is:
public static void write(){
try {
Workbook[] wbs = new Workbook[]{new XSSFWorkbook()};
Workbook workbook=wbs[0];
org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet();
System.out.println(sheet.getSheetName());
Row row = sheet.createRow(2);
for(int i=0;i<10;i++){
Cell cell=row.createCell(i);
cell.setCellValue("Sun System");
}
FileOutputStream fout=new FileOutputStream("D:/Test.Xlsx");
workbook.write(fout);
fout.close();
} catch (Exception e) {
}
}
The first thing U've to do :
When you're working with Excel 2007 format, its more wise to use XSSF-Implementations, because you've used abstract implementations. Always remember this when using any implementation.
To append to an existing file you need to reach the end of the rows in that particular workbook sheet. This can be achieved by:
int rows = sheet.getPhysicalNumberOfRows(); // or sheet.getLastRowNum();
After that you can create new cells with the XSSF- Implementation classes. For more information refer to this page
You should open the existing file instead of creating a new one if you want to append, see also this stackoverflow question:
Edit existing excel files using jxl api / Apache POI
You are creating a new workbook each time this is run youd want to create a FileInputStream with a file path to the excel file and then use that input stream to get the XSSF workbook you want to edit
FileInputStream fis = new FileInputStream(filePath);
XSSFWorkbook workBook = new XSSFWorkbook(fis);
then in order to get a specific sheet you simply just use the .getSheet or getSheetAt methods that are apart of workBook. then create and set cells

Categories

Resources