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.
Related
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.
List having data in this format
[{Row ID=7565.0, Product ID=test11223, Postal Code=98103.0}, {Row ID=7567.0, Product ID=test11213, Postal Code=98101.0}] Having more than 100 row ID record like this, I want to store that data in Excel in below format
Row Id Order ID Postal Code
7565 test11233 98103
7567 test11233 98101
Please help to share the code to write a above list data in excel. thnx
With Apache POI you can write any kind of MS Office files.
Here is a quick example how write cells with it.
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(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);
// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
I have been testing an application where i have to write a set of results to the excel file, the values are taken from the script. But the problem is that first I have to set the column headings like "Sl No" and "Name" after that I have to print the values against the particular cells. The thing is that am not able to write the results under the particular box.
I am new to apache poi. Can anyone help me with this issue.
Code for setting the excel and headings are shown below,
String FileName = "C://Users//Desktop//filename.xlsx";
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("Distributor");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Sl No");
Cell cell2 = row.createCell(1);
cell2.setCellValue("Name");
FileOutputStream outputStream = new FileOutputStream(new File(FileName));
workBook.write(outputStream);
outputStream.close();
I'm developing an app in java using POI, which writes data into excell sheet.
I want to write a new row when I have a new data (in order to assist the user to follow the data).
I dont want to close and reopen the excell file each time I have a new data to write.
The initilize code is:
FileOutputStream fileOut = new FileOutputStream(new File (excellFileName));
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
rowNum = 0;
HSSFRow rowhead = sheet.createRow((short)rowNum);
createRowColumns(rowhead, rowNum);
workbook.write(fileOut);
rowNum++;
Each time I have a new data, I'm using this code:
HSSFRow rowMsg = sheet.createRow((short)rowNum);
createRowColumns(rowMsg, rowNum);
workbook.write(fileOut);
rowNum++;
(createRowColumns mehtod sets the data (in seperate cells in a new: rowMsg)
The problem is that I cant see any rows in the excell file, except the first row (rowhead , row #0).
What Am I missing ?
(Pay attention that I dont want to close and reopen the file each time I have data to write)
Thanks
To write all rows you have to write to worksheet only once. So, you need to update your code as follows.
for(int index = 0; index < rowNum; rowNum++) {
HSSFRow rowMsg = sheet.createRow((short)rowNum);
createRowColumns(rowMsg, rowNum);
}
workbook.write(fileOut);
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.