Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map to Excel Sheet #1

Merged
merged 8 commits into from
Dec 18, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,89 @@ public <T> void addSheet(final Class<T> beanType, final List<T> rowObjects, fina
}
}

@Override
public void addSheet(final List<Map<String, String>> rowsData, final String inSheetName,
final List<String> inHeaders) {
// Sanity check
if (Objects.isNull(rowsData)) {
throw new IllegalArgumentException("AbstractSpreadsheetWriter :: Rows data map is NULL");
}
if (Objects.isNull(inHeaders)) {
throw new IllegalArgumentException("AbstractSpreadsheetWriter :: Headers list is NULL");
}

try {
final Sheet exSheet = workbook.getSheet(inSheetName);
if (Objects.nonNull(exSheet)) {
String errMsg = String.format("A Sheet with the passed name already exists : %s", inSheetName);
throw new IllegalArgumentException(errMsg);
}

// Create sheet
final Sheet sheet = Objects.isNull(inSheetName) || inSheetName.isBlank() //
? workbook.createSheet() //
: workbook.createSheet(inSheetName);
LOGGER.debug("Added new Sheet[name] to the workbook : {}", sheet.getSheetName());

// Header
final Row headerRow = sheet.createRow(0);
for (int i = 0; i < inHeaders.size(); i++) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use cellNo instead of i for consistency ?

final Cell cell = headerRow.createCell(i);
cell.setCellValue(inHeaders.get(i));
}

// Data Rows
for (int i = 0, rowNum = 1; i < rowsData.size(); i++, rowNum++) {
final Row row = sheet.createRow(rowNum);
final Map<String, String> rowData = rowsData.get(i);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

recommend below to hedge against null values

final Map<String, String> rowData = rowsData.getOrDefault(i, new HashMap<>());


for (int cellNo = 0; cellNo < inHeaders.size(); cellNo++) {
final String key = inHeaders.get(cellNo);
final String value = rowData.get(key);

final Cell cell = row.createCell(cellNo);
cell.setCellValue(value);
}
}
} catch (Exception ex) {
String errMsg = String.format("Error while preparing sheet with passed row objects : %s", ex.getMessage());
LOGGER.error(errMsg, ex);
}
}


@Override
public void createTemplate(final String sheetName, final List<String> headers) {
Copy link

@millij millij Dec 17, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Method name is ambiguous (based on the implementation)

Also, why not just use addRow method with empty list of rows data?

// Sanity check
if (Objects.isNull(headers)) {
throw new IllegalArgumentException("AbstractSpreadsheetWriter :: Headers list is NULL");
}

try {
final Sheet exSheet = workbook.getSheet(sheetName);
if (Objects.nonNull(exSheet)) {
String errMsg = String.format("A Sheet with the passed name already exists : %s", sheetName);
throw new IllegalArgumentException(errMsg);
}

// Create sheet
final Sheet sheet = Objects.isNull(sheetName) || sheetName.isBlank() //
? workbook.createSheet() //
: workbook.createSheet(sheetName);
LOGGER.debug("Added new Sheet[name] to the workbook : {}", sheet.getSheetName());

// Header
final Row headerRow = sheet.createRow(0);
for (int i = 0; i < headers.size(); i++) {
final Cell cell = headerRow.createCell(i);
cell.setCellValue(headers.get(i));
}
} catch (Exception ex) {
String errMsg = String.format("Error while preparing sheet with passed row objects : %s", ex.getMessage());
LOGGER.error(errMsg, ex);
}
}


// Sheet :: Append to existing

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
Expand Down Expand Up @@ -73,6 +74,29 @@ default <T> void addSheet(Class<T> beanClz, List<T> beans, List<String> headers)
<T> void addSheet(Class<T> beanClz, List<T> beans, String sheetName, List<String> headers);


/**
* This method will attempt to add a new sheet and add the rows of data from the rows data.
*
* @param rowsData List of row data as Map. The map elements contains the value for the header as
* key.
* @param sheetName Name of the Sheet. (set it to <code>null</code> for default name)
* @param headers a {@link List} of Header names to write in the file. <code>null</code> or empty
* list will default to all writable properties.
*/
void addSheet(List<Map<String, String>> rowsData, String sheetName, List<String> headers);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to be consistent, reorder the args

void addSheet(String sheetName, List<String> headers, List<Map<String, String>> rowsData);



/**
* This method will attempt to add a new empty sheet with just headers. The resulting sheet can be
* treated as a template to fill the data by users.
*
* @param sheetName Name of the Sheet. (set it to <code>null</code> for default name)
* @param headers a {@link List} of Header names to write in the file. <code>null</code> or empty
* list will default to all writable properties.
*/
void createTemplate(String sheetName, List<String> headers);


/**
* Writes the current Spreadsheet workbook to a file in the specified path.
*
Expand Down
85 changes: 85 additions & 0 deletions src/test/java/io/github/millij/poi/ss/writer/XlsWriterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.After;
import org.junit.Before;
Expand Down Expand Up @@ -115,4 +117,87 @@ public void test_write_xls_multiple_sheets() throws IOException {
gew.write(filepath_output_file);
}

@Test
public void test_write_map_as_xls_sheet() throws IOException {
final String filepath_output_file = _path_test_output.concat("map_2_sheets.xls");

// Excel Writer
LOGGER.info("test_write_map_as_xls_sheet :: Writing to file - {}", filepath_output_file);
SpreadsheetWriter gew = new XlsWriter();

// Headers
final List<String> headers = new ArrayList<>();
headers.add("Slno.");
headers.add("Name");
headers.add("Age");
headers.add("Gender");
headers.add("Height (mts)");
headers.add("Address");

// Data
final List<Map<String, String>> rowsDataMap = new ArrayList<>();
final Map<String, String> rowDataMap = new HashMap<>();
rowDataMap.put("Slno.", "1");
rowDataMap.put("Name", "foo");
rowDataMap.put("Age", "1");
rowDataMap.put("Gender", "Male");
rowDataMap.put("Height (mts)", "1.6");
rowDataMap.put("Address", "Chennai, India");
rowsDataMap.add(rowDataMap);

// Add Sheets
gew.addSheet(rowsDataMap, "test_sheet", headers);

// Write
gew.write(filepath_output_file);
}

@Test
public void test_write_map_as_xlsx_sheet_default_sheetname() throws IOException {
final String filepath_output_file = _path_test_output.concat("map_2_sheets_default_sheetname.xlsx");

// Excel Writer
LOGGER.info("test_write_map_as_xlsx_sheet_default_sheetname :: Writing to file - {}", filepath_output_file);
SpreadsheetWriter gew = new XlsWriter();

// Headers
final List<String> headers = new ArrayList<>();
headers.add("Slno.");
headers.add("Name");
headers.add("Age");
headers.add("Gender");
headers.add("Height (mts)");
headers.add("Address");

// Add Sheets
gew.addSheet(new ArrayList<>(), null, headers);

// Write
gew.write(filepath_output_file);
}

@Test
public void test_write_map_as_template_xls_sheet() throws IOException {
final String filepath_output_file = _path_test_output.concat("map_2_template_sheets.xls");

// Excel Writer
LOGGER.info("test_write_map_as_template_xls_sheet :: Writing to file - {}", filepath_output_file);
SpreadsheetWriter gew = new XlsWriter();

// Headers
final List<String> headers = new ArrayList<>();
headers.add("Slno.");
headers.add("Name");
headers.add("Age");
headers.add("Gender");
headers.add("Height (mts)");
headers.add("Address");

// Add Sheets
gew.createTemplate("test_sheet", headers);

// Write
gew.write(filepath_output_file);
}

}
85 changes: 85 additions & 0 deletions src/test/java/io/github/millij/poi/ss/writer/XlsxWriterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.After;
import org.junit.Before;
Expand Down Expand Up @@ -115,4 +117,87 @@ public void test_write_xlsx_multiple_sheets() throws IOException {
gew.write(filepath_output_file);
}

@Test
public void test_write_map_as_xlsx_sheet() throws IOException {
final String filepath_output_file = _path_test_output.concat("map_2_sheets.xlsx");

// Excel Writer
LOGGER.info("test_write_map_as_xlsx_sheet :: Writing to file - {}", filepath_output_file);
SpreadsheetWriter gew = new XlsWriter();

// Headers
final List<String> headers = new ArrayList<>();
headers.add("Slno.");
headers.add("Name");
headers.add("Age");
headers.add("Gender");
headers.add("Height (mts)");
headers.add("Address");

// Data
final List<Map<String, String>> rowsDataMap = new ArrayList<>();
final Map<String, String> rowDataMap = new HashMap<>();
rowDataMap.put("Slno.", "1");
rowDataMap.put("Name", "foo");
rowDataMap.put("Age", "1");
rowDataMap.put("Gender", "Male");
rowDataMap.put("Height (mts)", "1.6");
rowDataMap.put("Address", "Chennai, India");
rowsDataMap.add(rowDataMap);

// Add Sheets
gew.addSheet(rowsDataMap, "test_sheet", headers);

// Write
gew.write(filepath_output_file);
}

@Test
public void test_write_map_as_xlsx_sheet_default_sheetname() throws IOException {
final String filepath_output_file = _path_test_output.concat("map_2_sheets_default_sheetname.xlsx");

// Excel Writer
LOGGER.info("test_write_map_as_xlsx_sheet_default_sheetname :: Writing to file - {}", filepath_output_file);
SpreadsheetWriter gew = new XlsWriter();

// Headers
final List<String> headers = new ArrayList<>();
headers.add("Slno.");
headers.add("Name");
headers.add("Age");
headers.add("Gender");
headers.add("Height (mts)");
headers.add("Address");

// Add Sheets
gew.addSheet(new ArrayList<>(), null, headers);

// Write
gew.write(filepath_output_file);
}

@Test
public void test_write_map_as_template_xlsx_sheet() throws IOException {
final String filepath_output_file = _path_test_output.concat("map_2_template_sheets.xlsx");

// Excel Writer
LOGGER.info("test_write_map_as_template_xlsx_sheet :: Writing to file - {}", filepath_output_file);
SpreadsheetWriter gew = new XlsWriter();

// Headers
final List<String> headers = new ArrayList<>();
headers.add("Slno.");
headers.add("Name");
headers.add("Age");
headers.add("Gender");
headers.add("Height (mts)");
headers.add("Address");

// Add Sheets
gew.createTemplate("test_sheet", headers);

// Write
gew.write(filepath_output_file);
}

}