Skip to content

Commit

Permalink
[plugin-excel] Add ability to specify cells type during data creation
Browse files Browse the repository at this point in the history
  • Loading branch information
web-flow committed Jun 21, 2024
1 parent 9a34c6b commit 32a329c
Show file tree
Hide file tree
Showing 8 changed files with 356 additions and 40 deletions.
28 changes: 14 additions & 14 deletions docs/modules/plugins/pages/plugin-excel.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -101,41 +101,41 @@ Examples:

== Steps

=== Create excel file containing sheet with specified content
=== Create Excel file containing sheet with specified content

Create temporary excel file with specified content and save the path to the variable
Create temporary Excel file with specified content and save the path to the variable

[source,gherkin]
----
When I create temporary excel file with content:$content and put path to $scopes variable `$variableName`
----

* `$content` - The data to be put to the excel file. Any valid xref:ROOT:glossary.adoc#_examplestable[ExamplesTable]
* `$content` - The table with data of xref:partial$excel-cell-types.adoc[different types] to be put to the Excel file. Any valid xref:ROOT:glossary.adoc#_examplestable[ExamplesTable].
* `$scopes` - xref:commons:variables.adoc#_scopes[The comma-separated set of the variables scopes].
* `$variableName` - The variable name
* `$variableName` - The variable name.

.Create temporary excel file
[source,gherkin]
----
When I create temporary excel file with content:
|key1 |key2 |
|value1|value2|
|key1 |key2 |
|value1|#{withCellType(Numeric, 123.321 format #.000)} |
and put path to scenario variable `path`
----

=== Create excel file containing sheet with specified name and content
=== Create Excel file containing sheet with specified name and content

Create temporary excel file containing sheet with specified name and content and save the file's path to the variable
Create temporary Excel file containing sheet with specified name and content and save the file's path to the variable

[source,gherkin]
----
When I create temporary excel file containing sheet with name `$sheetName` and content:$content and put its path to $scopes variable `$variableName`
----

* `$sheetName` - Then name of the Excel sheet.
* `$content` - The data to be put to the excel file. Any valid xref:ROOT:glossary.adoc#_examplestable[ExamplesTable]
* `$content` - The table with data of xref:partial$excel-cell-types.adoc[different types] to be put to the Excel file. Any valid xref:ROOT:glossary.adoc#_examplestable[ExamplesTable].
* `$scopes` - xref:commons:variables.adoc#_scopes[The comma-separated set of the variables scopes].
* `$variableName` - The variable name
* `$variableName` - The variable name.

.Create temporary excel file
[source,gherkin]
Expand All @@ -148,18 +148,18 @@ When I create temporary excel file containing sheet with name `movies` and conte
and put its path to scenario variable `movies-path`
----

=== Add sheet to existing excel file
=== Add sheet to existing Excel file

Add new sheet with the specified name and content to the existing excel file.
Add new sheet with the specified name and content to the existing Excel file.

[source,gherkin]
----
When I add sheet with name `$sheetName` and content:$content to excel file at path `$path`
----

* `$sheetName` - Then name of the sheet.
* `$content` - The data to put into the sheet. Any valid xref:ROOT:glossary.adoc#_examplestable[ExamplesTable].
* `$path` - The path to existing excel file.
* `$content` - The table with data of xref:partial$excel-cell-types.adoc[different types] to put into the sheet. Any valid xref:ROOT:glossary.adoc#_examplestable[ExamplesTable].
* `$path` - The path to existing Excel file.

.Add sheet with pets
[source,gherkin]
Expand Down
77 changes: 77 additions & 0 deletions docs/modules/plugins/partials/excel-cell-types.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
== Excel cell types

[cols="1,3,3", options="header"]
|===

|Type
|Usage example
|Description

|STRING
|`String value`

`#{withCellType(String, String value)}`
|Default cells type. Used if the cell type is not specified explicitly

|FORMULA
|`\#{withCellType(Formula, DOLLAR(A2))}`

`#{withCellType(Formula, A2+A3)}`
|https://support.microsoft.com/en-us/office/data-types-in-data-models-e2388f62-6122-4e2b-bcad-053e3da9ba90[Excel formulas]

|DATE
|`\#{withCellType(Date, 03/31/2024)}` - date with default date input format `MM/dd/yyyy` and default cell format `m/d/yy`. Output `3/31/24`

`#{withCellType(Date, 31-Mar-2024 input dd-MMM-yyyy)}` - date with custom date input format `dd-MMM-yyyy` and default cell format `m/d/yy`. Output `3/31/24`

`\#{withCellType(Date, 03/31/2024 format m.d.yyyy h:mm)}` - date with default date input format `MM/dd/yyyy` and custom cell format `m.d.yyyy h:mm`. Output `3.31.2024 0:00`

`#{withCellType(Date, 2024/03/31 13:04 input yyyy/MM/dd HH:mm format m.d.yy h:mm)}` - date with custom date input and cell formats. Output `3.31.24 13:04`

|Excel date.

Optional parameters:

`input` - the input date format based on the https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/format/DateTimeFormatter.html#patterns[date/time format]. Default value is `MM/dd/yyyy`

`format` - the output https://support.microsoft.com/en-us/office/format-numbers-as-dates-or-times-418bd3fe-0577-47c8-8caa-b4d30c528309[cell date format] in Excel. Default value is `m/d/yy`

|BOOLEAN
|`#{withCellType(Boolean, false)}`
|Boolean cell type

|NUMERIC
|`\#{withCellType(Numeric, 128)}` - output `128.0`

`#{withCellType(Numeric, 32768 format \#,##0.00)}` - the number with `,` thousands separator and two decimal places. Output `32,768.00`
|Number cell type

Optional parameters:

`format` - the current https://support.microsoft.com/en-us/office/number-format-codes-5026bbd6-04bc-48cd-bf33-80f18b4eae68[cell number format]. Default value `#.0`

|===

=== Cells type for column

Cells type can be specified for all values in column using the next column name format: `#{withColumnCellsType(<values-type>, <column-name>)`. The types specified in individual cells will have priority.

.Create Excel file with typed column
----
When I create temporary excel file with content:
|#{withColumnCellsType(date, multi-type column)} |
|31-Mar-2024 input dd-MMM-yyyy |
|#{withCellType(Numeric, 100500 format #,##0.00)} |
|#{withCellType(Boolean, true)} |
|2024/03/31 13:04 input yyyy/MM/dd HH:mm format m.d.yy h:mm |
and put path to scenario variable `path`
----

Data from output Excel file:
----
|multi-type column |
|3/31/24 |
|100,500.00 |
|TRUE |
|3.31.24 13:04 |
----
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,28 @@
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;

import org.apache.commons.lang3.EnumUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jbehave.core.model.ExamplesTable;
import org.vividus.model.CellType;
import org.vividus.util.DateUtils;

public final class ExcelSheetWriter
{
private static final Pattern HEADER_WITH_TYPE_PATTERN = Pattern
.compile("#\\{withColumnCellsType\\(([^,]+),\\h*(.*)\\)}");
private static final Pattern CELL_WITH_TYPE_PATTERN = Pattern.compile("#\\{withCellType\\(([^,]+),\\h*(.*)\\)}");

private ExcelSheetWriter()
{
}
Expand All @@ -41,14 +52,16 @@ private ExcelSheetWriter()
* @param path path of Excel file to create
* @param sheetName sheet name, if not specified the default name will be determined by underlying excel library
* @param content any valid ExamplesTable
* @param dateUtils Date utilities to parse dates for DATE cell types
*/
public static void createExcel(Path path, Optional<String> sheetName, ExamplesTable content) throws IOException
public static void createExcel(Path path, Optional<String> sheetName, ExamplesTable content, DateUtils dateUtils)
throws IOException
{
try (XSSFWorkbook workbook = new XSSFWorkbook();
OutputStream fileOut = Files.newOutputStream(path))
{
XSSFSheet sheet = sheetName.map(workbook::createSheet).orElseGet(workbook::createSheet);
fillData(content, sheet);
fillData(content, sheet, workbook, dateUtils);
workbook.write(fileOut);
}
}
Expand All @@ -58,30 +71,70 @@ public static void createExcel(Path path, Optional<String> sheetName, ExamplesTa
* @param path path of existing Excel file
* @param sheetName sheet name
* @param content any valid ExamplesTable
* @param dateUtils Date utilities to parse dates for DATE cell types
*/
public static void addSheetToExcel(Path path, String sheetName, ExamplesTable content) throws IOException
public static void addSheetToExcel(Path path, String sheetName, ExamplesTable content, DateUtils dateUtils)
throws IOException
{
try (InputStream fileInput = Files.newInputStream(path);
XSSFWorkbook workbook = new XSSFWorkbook(fileInput);
OutputStream fileOut = Files.newOutputStream(path))
{
fillData(content, workbook.createSheet(sheetName));
fillData(content, workbook.createSheet(sheetName), workbook, dateUtils);
workbook.write(fileOut);
}
}

private static void fillData(ExamplesTable content, XSSFSheet sheet)
private static void fillData(ExamplesTable content, XSSFSheet sheet, XSSFWorkbook workbook, DateUtils dateUtils)
{
fillRow(sheet, 0, content.getHeaders());
ArrayList<CellType> columTypes = new ArrayList<>();
fillRow(sheet, workbook, 0, content.getHeaders(), columTypes, dateUtils);
IntStream.range(0, content.getRowCount()).forEach(rowIndex -> {
List<String> cells = content.getRowValues(rowIndex, true);
fillRow(sheet, rowIndex + 1, cells);
fillRow(sheet, workbook, rowIndex + 1, cells, columTypes, dateUtils);
});
}

private static void fillRow(XSSFSheet sheet, int rowIndex, List<String> cells)
private static void fillRow(XSSFSheet sheet, XSSFWorkbook workbook, int rowIndex, List<String> cells,
ArrayList<CellType> columTypes, DateUtils dateUtils)
{
Row row = sheet.createRow(rowIndex);
IntStream.range(0, cells.size()).forEach(index -> row.createCell(index).setCellValue(cells.get(index)));
IntStream.range(0, cells.size()).forEach(index ->
{
if (rowIndex == 0)
{
String headerFromExampleTable = cells.get(index);
Cell cellExcel = row.createCell(index);
Matcher headerTypeMatcher = HEADER_WITH_TYPE_PATTERN.matcher(headerFromExampleTable);

if (headerTypeMatcher.matches())
{
columTypes.add(EnumUtils.getEnumIgnoreCase(CellType.class, headerTypeMatcher.group(1)));
cellExcel.setCellValue(headerTypeMatcher.group(2));
}
else
{
cellExcel.setCellValue(headerFromExampleTable);
columTypes.add(CellType.STRING);
}
}
else
{
String cellContentFromExampleTable = cells.get(index);
Cell cellExcel = row.createCell(index);
Matcher cellTypeMatcher = CELL_WITH_TYPE_PATTERN.matcher(cellContentFromExampleTable);
if (cellTypeMatcher.matches())
{
CellType type = EnumUtils.getEnumIgnoreCase(CellType.class, cellTypeMatcher.group(1));
String cellContent = cellTypeMatcher.group(2);
type.setCellValue(workbook, cellExcel, cellContent, dateUtils);
}
else
{
CellType type = columTypes.get(index);
type.setCellValue(workbook, cellExcel, cellContentFromExampleTable, dateUtils);
}
}
});
}
}
111 changes: 111 additions & 0 deletions vividus-plugin-excel/src/main/java/org/vividus/model/CellType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* Copyright 2019-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.vividus.model;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.vividus.util.DateUtils;

public enum CellType
{
STRING
{
@Override
public void setCellValue(XSSFWorkbook workbook, Cell cell, String value, DateUtils dateUtils)
{
cell.setCellValue(value);
}
},
FORMULA
{
@Override
public void setCellValue(XSSFWorkbook workbook, Cell cell, String value, DateUtils dateUtils)
{
cell.setCellFormula(value);
}
},
DATE
{
@Override
public void setCellValue(XSSFWorkbook workbook, Cell cell, String value, DateUtils dateUtils)
{
Matcher valueMatcher = INCOMING_VALUE_PATTERN.matcher(value);
if (!valueMatcher.matches())
{
throw new IllegalArgumentException("The date value isn't specified");
}
Matcher inputFormatMatcher = INPUT_FORMAT_PATTERN.matcher(value);
Matcher sellFormatMatcher = SELL_FORMAT_PATTERN.matcher(value);

String inputFormat = inputFormatMatcher.matches() ? inputFormatMatcher.group(1).trim() : "MM/dd/yyyy";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(inputFormat, Locale.ENGLISH);
ZonedDateTime zonedDateTime = dateUtils.parseDateTime(valueMatcher.group(1).trim(), formatter);
LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
cell.setCellValue(localDateTime);

CreationHelper createHelper = workbook.getCreationHelper();
CellStyle cellStyle = workbook.createCellStyle();
String sellFormat = sellFormatMatcher.matches() ? sellFormatMatcher.group(1).trim() : "m/d/yy";
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(sellFormat));
cell.setCellStyle(cellStyle);
}
},
BOOLEAN
{
@Override
public void setCellValue(XSSFWorkbook workbook, Cell cell, String value, DateUtils dateUtils)
{
cell.setCellValue(Boolean.parseBoolean(value));
}
},
NUMERIC
{
@Override
public void setCellValue(XSSFWorkbook workbook, Cell cell, String value, DateUtils dateUtils)
{
Matcher valueMatcher = INCOMING_VALUE_PATTERN.matcher(value);
if (!valueMatcher.matches())
{
throw new IllegalArgumentException("The numeric value isn't specified");
}
Matcher sellFormatMatcher = SELL_FORMAT_PATTERN.matcher(value);

cell.setCellValue(Double.parseDouble(valueMatcher.group(1).trim()));

CreationHelper createHelper = workbook.getCreationHelper();
CellStyle cellStyle = workbook.createCellStyle();
String sellFormat = sellFormatMatcher.matches() ? sellFormatMatcher.group(1).trim() : "#.0";
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(sellFormat));
cell.setCellStyle(cellStyle);
}
};

private static final Pattern INCOMING_VALUE_PATTERN = Pattern.compile("^(.+?)(?=format|input|$).*");
private static final Pattern INPUT_FORMAT_PATTERN = Pattern.compile(".+input\\h+(.*?)(?=format|$).*");
private static final Pattern SELL_FORMAT_PATTERN = Pattern.compile(".+format\\h+(.*?)(?=input|$).*");

public abstract void setCellValue(XSSFWorkbook workbook, Cell cell, String value, DateUtils dateUtils);
}
Loading

0 comments on commit 32a329c

Please sign in to comment.