Need help! I am trying to code a simple function that could return the data from an excel source.
I am trying to create a list of Maps of data from excel file but the list that I am getting has the same values. All value are the same.
Here is my code:
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class ExcelReaderFinal {
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\username\\Downloads\\TestFile.xlsx";
FileInputStream fis = new FileInputStream(path);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
int lastRow = sheet.getLastRowNum()-5;
int lastColumn = 3;
Map<String, Object> dataMap = new HashMap<String, Object>();
ArrayList<Map<String, Object>> dataList = new ArrayList<>();
for(int j=0; j<=lastRow; j++){
for(int i=0; i<=lastColumn; i++) {
Row row = sheet.getRow(4);
Cell keyCell = row.getCell(i);
Row val = sheet.getRow(5+j);
Cell valueCell = val.getCell(i);
String value = valueCell.getStringCellValue().trim();
String key = keyCell.getStringCellValue().trim();
dataMap.put(key, value);
}
dataList.add(dataMap);
}
System.out.println(dataList);
}
}
my actual output is like this:
[{Negative Val=0, Account Number=121312C, Positive Val=20,000,000.00, Banko=RCBC}, {Negative Val=0, Account Number=121312C, Positive Val=20,000,000.00, Banko=RCBC}, {Negative Val=0, Account Number=121312C, Positive Val=20,000,000.00, Banko=RCBC}]
but my expected output is like this:
And here is my excel file source:
In Summary:
I want to get all the data in excel file in list format
that list should be sorted based on the arrangement of columns from excel.
Thank you so much!!
Related
I am trying to create an Excel sheet that contains an Excel table using Java with the Apache POI library but I couldn't get a result file that is readable by Microsoft Excel 2016 (Office 365). This is my code:
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
class Scratch {
public static void main(String[] args) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Table Sheet");
XSSFRow row0 = sheet.createRow(0);
row0.createCell(0).setCellValue("#");
row0.createCell(1).setCellValue("Name");
XSSFRow row1 = sheet.createRow(1);
row1.createCell(0).setCellValue("1");
row1.createCell(1).setCellValue("Foo");
XSSFRow row2 = sheet.createRow(2);
row2.createCell(0).setCellValue("2");
row2.createCell(1).setCellValue("Bar");
AreaReference area = workbook.getCreationHelper().createAreaReference(
new CellReference(row0.getCell(0)),
new CellReference(row2.getCell(1))
);
sheet.createTable(area);
try(FileOutputStream file = new FileOutputStream(new File("workbook.xlsx"))) {
workbook.write(file);
}
}
}
The code runs fine but when I open the output file in Excel I get a message that the file has unreadable content.
I have tried running the official sample and the result is the same. The official sample can be found here: https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateTable.java
I need to know the minimum code required to get a readable table.
I am using version 4.0.0 of Apache POI with Oracle JavaSE JDK 1.8.0_172 on Windows 10.
Not sure what happens with the "official sample" codes always. They seems not even be tested.
The CreateTable uses XSSFTable table = sheet.createTable(reference); which creates a table having 3 columns as given from the area reference. But all of those have id 1, so we need repairing. And of course the columns should not be created again then.
So repaired sample code would be:
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFTableStyleInfo;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* Demonstrates how to create a simple table using Apache POI.
*/
public class CreateTable {
public static void main(String[] args) throws IOException {
try (Workbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
// Set which area the table should be placed in
AreaReference reference = wb.getCreationHelper().createAreaReference(
new CellReference(0, 0), new CellReference(2, 2));
// Create
XSSFTable table = sheet.createTable(reference); //creates a table having 3 columns as of area reference
// but all of those have id 1, so we need repairing
table.getCTTable().getTableColumns().getTableColumnArray(1).setId(2);
table.getCTTable().getTableColumns().getTableColumnArray(2).setId(3);
table.setName("Test");
table.setDisplayName("Test_Table");
// For now, create the initial style in a low-level way
table.getCTTable().addNewTableStyleInfo();
table.getCTTable().getTableStyleInfo().setName("TableStyleMedium2");
// Style the table
XSSFTableStyleInfo style = (XSSFTableStyleInfo) table.getStyle();
style.setName("TableStyleMedium2");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
style.setFirstColumn(false);
style.setLastColumn(false);
style.setShowRowStripes(true);
style.setShowColumnStripes(true);
// Set the values for the table
XSSFRow row;
XSSFCell cell;
for (int i = 0; i < 3; i++) {
// Create row
row = sheet.createRow(i);
for (int j = 0; j < 3; j++) {
// Create cell
cell = row.createCell(j);
if (i == 0) {
cell.setCellValue("Column" + (j + 1));
} else {
cell.setCellValue((i + 1.0) * (j + 1.0));
}
}
}
// Save
try (FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx")) {
wb.write(fileOut);
}
}
}
}
Btw.: My code from How to insert a table in ms excel using apache java poi works as well using apache poi 4.0.0. The sheet.createTable() is deprecated. So do using XSSFTable table = sheet.createTable(null); instead. Because the area as well as all other things is set using low level classes. Not even more code than the new example though.
I am still new to java. I am having a bit problems with the java syntax.
My Program should do the following procedure:
1) It takes a csv file as an input.
2) It takes an excel file as an input.
3) It should iterate over the first columns of the two files where the dates are written.
4) Update the excel file by adding the information from the csv sheet and save its changes.
I have a https://onedrive.live.com/?cid=24b4fceb4f4e4098&id=24B4FCEB4F4E4098%213018&authkey=%21AKKzaZsJ5pkd5NE
where I have the two input examples and how the result excel sheet should look like.
Two Input files:
export-csv-input.csv
export-excel-input.xlsx
The updated excel file should look like:
export-excel-output.xlsx
My Java Code yet:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CsvToExcelConverter {
public static final String SAMPLE_XLSX_FILE_PATH =
"C:/Users/blawand/Desktop/CSV_to_Excel/export-excel-test.xlsx";
public static final String SAMPLE_CSV_FILE_PATH =
"C:/Users/blawand/Desktop/CSV_to_Excel/export-csv-test.csv";
public static List<String> dates_csv = new ArrayList<>();
public static List<String> dates_excel = new ArrayList<>();
public static void main(String[] args) throws IOException,
InvalidFormatException {
try (Reader reader =
Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);)
{
for (CSVRecord csvRecord : csvParser) {
// Accessing Values by Column Index
String name = csvRecord.get(0);
dates_csv.add(name);
}
dates_csv.remove(0);
}
FileInputStream fsIP = new FileInputStream(new
File(SAMPLE_XLSX_FILE_PATH));
/*
* ==================================================================
Iterating over all the
* rows and columns in a Sheet (Multiple ways)
* ==================================================================
*/
// Getting the Sheet at index zero
XSSFWorkbook workbook = new XSSFWorkbook(fsIP);
XSSFSheet sheet = workbook.getSheetAt(0);
// Get the Cell at index 2 from the above row
// Cell cell1 = sheet.getRow(1).getCell(0);
// for (int i = 0; i < dates_excel.size(); i++) {
// XSSFRow rowtest = sheet.createRow((short) i + 1);
// rowtest.createCell(0).setCellValue(dates_csv.get(i));
//
// }
// cell1.setCellValue(dates_csv.get(0));
// Create a DataFormatter to format and get each cell's value as
String
DataFormatter dataFormatter = new DataFormatter();
for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++)
{
Row row = sheet.getRow(rowIndex);
if (row != null) {
Cell cell = row.getCell(0); // getColumn(0)
if (cell != null) {
// Found column and there is value in the cell.
// String cellValueMaybeNull = cell.getStringCellValue();
String cellValueMaybeNull =
dataFormatter.formatCellValue(cell);
// String to number set
dates_excel.add(cellValueMaybeNull);
}
}
}
System.out.println(dates_csv);
System.out.println(dates_csv.size());
System.out.println(dates_excel);
System.out.println(dates_excel.size());
while (dates_excel == dates_excel) {
System.out.println("Yes");
break;
}
fsIP.close();
FileOutputStream output_file = new FileOutputStream(new
File(SAMPLE_XLSX_FILE_PATH));
workbook.write(output_file);
output_file.close();
}
}
I read already the two files but i am having problems with updating the excel file and adding the project names to the correct dates. And if the same date has been written two or more times in the csv sheet.
Which information would you like also to know?
I would be thankful for every help or advice!
I have an example for you, mostly explained by code comments. Nevertheless, the code basically does the following:
Takes file paths of the xlsx and csv file in the constructor.
When updating, it first reads the content of the csv file into a Map with a LocalDate as key and a List<String> as values.
Then it goes through the rows of the workbook skipping the header row and comparing the dates in column one with the keys of the Map<LocalDate, List<String>>. If the map contains that key, it starts checking the cells in that row for present values and keeps them in a list in order to not write them later.
Then it starts writing the values into the cells of the row with the key date.
I hope this helps.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CsvXlsxUpdater {
private static final DateTimeFormatter DATE_TIME_FORMATTER_CSV = DateTimeFormatter.ofPattern("dd.MM.yyyy");
private Path csvFilePath;
private Path xlsxFilePath;
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private Map<LocalDate, List<String>> csvContent = new TreeMap<LocalDate, List<String>>();
private ZoneId zoneId = ZoneId.systemDefault();
public CsvXlsxUpdater(String pathToCsvFile, String pathToXlsxFile) {
csvFilePath = Paths.get(pathToCsvFile);
xlsxFilePath = Paths.get(pathToXlsxFile);
}
/**
* Reads the content of the csv file into the corresponding class variable,
* which is a {#link TreeMap} that has a {#link LocalDate} as key and a
* {#link List<String>} as values.
*/
private void readCsvContent() {
List<String> csvLines;
try {
csvLines = Files.readAllLines(csvFilePath);
for (int i = 1; i < csvLines.size(); i++) {
String line = csvLines.get(i);
String[] splitValues = line.split(",");
if (splitValues.length > 1) {
List<String> lineValues = Arrays.asList(splitValues);
List<String> projects = getProjectValuesFrom(lineValues);
LocalDate localDate = LocalDate.parse(lineValues.get(0), DATE_TIME_FORMATTER_CSV);
if (csvContent.containsKey(localDate)) {
projects.forEach((String project) -> {
List<String> csvProjects = csvContent.get(localDate);
if (!csvProjects.contains(project)) {
csvProjects.add(project);
}
});
} else {
csvContent.put(localDate, projects);
}
} else {
LocalDate localDate = LocalDate.parse(splitValues[0], DATE_TIME_FORMATTER_CSV);
csvContent.put(localDate, new ArrayList<String>());
}
}
} catch (IOException e) {
System.err.println("CANNOT FIND OR READ CSV FILE: " + e.getMessage());
e.printStackTrace();
} catch (UnsupportedOperationException e) {
System.err.println("UNSUPPORTED OPERATION: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Gets the corresponding {#link LocalDate} from a given (and deprecated)
* {#link Date}
*
* #param date the deprecated {#link Date} object
* #return the corresponding {#link LocalDate}
*/
private LocalDate parseLocalDateFrom(Date date) {
Instant instantDate = date.toInstant();
return instantDate.atZone(zoneId).toLocalDate();
}
/**
* Takes a list of read values from the csv file and returns a list containing
* all the values of the given list <strong>except from the first
* element</strong>, which is a {#link String} representation of a date and
* should be treated differently in this context.
*
* #param values the original list of {#link String}s
* #return another list without the first element of the given list
*/
private List<String> getProjectValuesFrom(List<String> values) {
List<String> projectValues = new ArrayList<String>();
for (int i = 1; i < values.size(); i++) {
String value = values.get(i);
if (!value.equals("")) {
projectValues.add(value);
}
}
return projectValues;
}
/**
* Updates the workbook with the values read from the csv file
*/
public void updateWorkbook() {
readCsvContent();
try {
FileInputStream fis = new FileInputStream(xlsxFilePath.toAbsolutePath().toString());
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
// iterate over the rows
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
XSSFRow row = (XSSFRow) rowIterator.next();
if (row.getRowNum() == 0) {
// skip this or set updated headers
} else {
// check if the csvContent contains the value of cell(0)
LocalDate dateKey = parseLocalDateFrom(row.getCell(0).getDateCellValue());
if (csvContent.containsKey(dateKey)) {
// if yes, get list-value of the key
List<String> values = csvContent.get(dateKey);
// check if there are values
if (values != null) {
if (values.size() > 0) {
// if there are, then go checking the cell values
List<String> projectsInXlsx = new ArrayList<String>();
Iterator<Cell> cellIterator = row.cellIterator();
int lastColumnIndex = 1;
// go through all cells with a value except from the first one
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// skip the first column as it contains the date
if (cell.getColumnIndex() != 0) {
lastColumnIndex = cell.getColumnIndex();
System.out.println("Accessing cell in column " + lastColumnIndex);
// if there is a cell with a value
if (cell.getStringCellValue() != null) {
if (!cell.getStringCellValue().equals("")) {
// check if the value in the cell is also in the csv values
if (values.contains(cell.getStringCellValue())) {
projectsInXlsx.add(cell.getStringCellValue());
lastColumnIndex++;
}
}
}
}
}
// now go through the values of the csv file
int offset = 0; // cell column offset for more than one entry per date
for (String value : values) {
if (!projectsInXlsx.contains(value)) {
// create a cell after the last one with a value
row.createCell(lastColumnIndex + offset).setCellValue(value);
offset++;
}
}
}
}
}
}
}
fis.close();
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFilePath.toAbsolutePath().toString());
workbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In a main method, you would just have to call the constructor, pass the file paths as Strings and then call the updateWorkbook() method, because it internally reads the csv first.
Example:
public class CsvXlsxMain {
private static final String CSV_FILE_PATH = "S:\\ome\\example\\path\\to\\csv-input.csv";
private static final String XLSX_FILE_PATH = "S:\\ome\\example\\path\\to\\excel-input.xlsx";
public static void main(String[] args) {
CsvXlsxUpdater cxu = new CsvXlsxUpdater(CSV_FILE_PATH, XLSX_FILE_PATH);
cxu.updateWorkbook();
}
}
Please keep in mind that this CODE IS NOT FULLY TESTED, there may be problems with alternating resources in future
If you need, go testing it with various xlsx and csv inputs that fit your requirements.
I haven't used any library to parse the csv file!
I hope this helps you a littleā¦
Please find the attached code snippet and please help me to proceed with this. I am trying to read data from one excel and then write the same to another excel , while trying to write the file it's stopping the code. When I tried debugging I could see that value is properly fetched but write is not working.
package Export;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestExport
{
XSSFWorkbook xlsxworkbook;
HSSFWorkbook xlsworkbook;
XSSFWorkbook xlsxworkbook1;
HSSFWorkbook xlsworkbook1;
Sheet sheet;
Sheet sheet1;
TestExport(){
xlsxworkbook=null;
xlsworkbook=null;
sheet=null;
xlsxworkbook1=null;
xlsworkbook1=null;
sheet1=null;
}
public void readExcel(String filePath,String fileName,String sheetName,String filePath1,String fileName1,String sheetName1)
{
try{
FileInputStream fs=new FileInputStream(new File("C:\\Users\\Susmitha-Phases\\Desktop\\TestWorkbook.xlsx"));
FileOutputStream fi=new FileOutputStream(new File("C:\\Users\\Susmitha-Phases\\Desktop\\TestWorkbook1.xlsx"));
fs.toString();
if(fileName.toLowerCase().endsWith("xlsx")){
xlsxworkbook = new XSSFWorkbook(fs);
sheet=xlsxworkbook.getSheet(sheetName);
xlsxworkbook1 = new XSSFWorkbook();
sheet1=xlsxworkbook.getSheet(sheetName1);
}
else{
xlsworkbook=new HSSFWorkbook(fs);
sheet=xlsworkbook.getSheet(sheetName);
xlsworkbook1=new HSSFWorkbook();
sheet1=xlsworkbook.getSheet(sheetName1);
}
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
//Create a loop over all the rows of excel file to read it
for (int i = 0; i < rowCount+1; i++)
{
Row row = sheet.getRow(i);
Row row1=sheet1.getRow(i);
//Create a loop to print cell values in a row
for (int j = 0; j < row.getLastCellNum(); j++)
{
String temp= row.getCell(j).getStringCellValue();
row1.createCell(i).setCellValue(temp);
//Print Excel data in console
System.out.print(row1.getCell(j).getStringCellValue()+"|| ");
xlsworkbook.write(fi);
//System.out.print(row.getCell(j).getStringCellValue()+"|| ");
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws IOException{
//Create an object of ReadGuru99ExcelFile class
TestExport objExcelFile = new TestExport();
//Prepare the path of excel file
String filePath = System.getProperty("C:\\Users\\Susmitha-Phases\\Desktop\\TestWorkbook.xlsx");
String filePath1 = System.getProperty("C:\\Users\\Susmitha-Phases\\Desktop\\TestWorkbook1.xlsx");
//Call read file method of the class to read data
objExcelFile.readExcel(filePath,"TestWorkbook.xlsx","Sheet1",filePath1,"TestWorkbook1.xlsx","Sheet1");
}
}
There are some problem with your code it possible throw null pointer exception
You never created the instance for xlsworkbook in your class when the file type xlsx and trying to write the file . which is wrong will throw definitely null pointer exception. so You must change the logic while writing which file type should be write . Probably you can check file type and write the file.
I am using apache poi to extract data from excel sheet and trying to save extracted values in an array.
I am getting java.lang.NullPointerException error.
I searched about it, and apparently this exception triggered when you try to assign a value to an object whose value is null.
I tried to look up many example, but most example codes just print out cell value. I want to save them in an array to perform some calculation.
package exceltotext;
import java.io.*;
import java.lang.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class convert {
#SuppressWarnings("null")
public static void main(String[] args) throws IOException {
double [] modify = null ;
FileInputStream fs = new FileInputStream(new File ("Book1.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(fs);
XSSFSheet sheet = wb.getSheetAt(0);
FormulaEvaluator formulaevaluater = wb.getCreationHelper().createFormulaEvaluator();
for (Row row:sheet)
{
int num = 0;
for(Cell cell : row){
switch (formulaevaluater.evaluate(cell).getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
modify [num] = ( cell.getNumericCellValue());
num += num;
}
System.out.println(modify[num]);
}
}
}
}
Your modify array is null so num += num; will give you NPE. You need to create this array with for an egzample double [] modify = new double[1000]; instead of double [] modify = null ;
I think, first you need to define the rows, from where you are trying to extract the values.
Apache Poi have option for row i.e XSSFRow.
PS i would personally recommend HSSF instead of XSSF , hence HSSF is for new version of excel. You need to change the file extension name to use in HSSF if the same document is being used by XSSF (Cause of Version Incompatibility).
I have an ArrayList of Strings which is quite huge(approximately over 500k and more of items).
Is there any possibility to speed up writing this array to an excel file? Right now it takes a while and I have no idea if I did everything that I could(Maybe it is a problem with .get method?).
Please refer to the following code(please do not pay attation to details- this class is created only for test purposes):
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Tests {
private static final String ADDRESS = "./result/file.xlsx";
public static void readAndWriteAData(int counterOfExecutions, List<String> listOfResults) throws IOException{
File file = new File(ADDRESS);
if(file.exists()&&!file.isDirectory()){
file.delete();
}
#SuppressWarnings("resource")
Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(ADDRESS);
wb.write(fileOut);
fileOut.close();
Sheet sheet = wb.createSheet("1");
Row row;
Cell cell;
int add = 0;
System.out.println("Start of filling excel file");
for(int i=0; i<counterOfExecutions;i++){
row = sheet.createRow(i);
for(int j=0; j<5; j++){
cell = row.createCell(j);
cell.setCellValue(listOfResults.get(j+add));
}
add+=5;
}
FileOutputStream fileOutputSecond = new FileOutputStream(file);
wb.write(fileOutputSecond);
fileOutputSecond.close();
System.out.println("File "+ADDRESS+" has been created.");
}
public static void main(String[] args) throws IOException {
System.out.println("Start of creating ArrayList");
List<String> lista = new ArrayList<>();
for(int i = 1 ; i<550000;i++){
lista.add("nic "+i);
}
System.out.println("ArrayList has been filled");
readAndWriteAData(100999, lista);
System.out.println("The End");
}
}
Thanks a lot in advance for any hints! :)
Please try to use SXSSFWorkbook. which will be more efficient for the better usage of it try to see the Apache POI 3.8 API
Just Look at the example
how-to-read-write-xlsx-file-in-java-apache-poi-example
Please refer below
How to speed up excel reading/writing
Probably this addresses the same problem; The logger configuration did the trick for me.