├── vaadin-excel-exporter-demo ├── src │ └── main │ │ ├── resources │ │ └── org │ │ │ └── vaadin │ │ │ └── addons │ │ │ └── README │ │ ├── webapp │ │ ├── META-INF │ │ │ ├── MANIFEST.MF │ │ │ └── context.xml │ │ └── VAADIN │ │ │ └── themes │ │ │ └── demo │ │ │ ├── favicon.ico │ │ │ ├── images │ │ │ └── radial-gradient.png │ │ │ └── styles.scss │ │ └── java │ │ └── org │ │ └── vaadin │ │ └── addons │ │ └── excelexporter │ │ └── demo │ │ ├── data │ │ └── DataModelGenerator.java │ │ ├── DataModel.java │ │ └── DemoUI.java └── pom.xml ├── vaadin-excel-exporter ├── src │ └── main │ │ ├── resources │ │ └── org │ │ │ └── vaadin │ │ │ └── addons │ │ │ ├── public │ │ │ └── vaadin-excel-exporter │ │ │ │ └── styles.css │ │ │ └── WidgetSet.gwt.xml │ │ └── java │ │ └── org │ │ └── vaadin │ │ └── addons │ │ └── excelexporter │ │ ├── configuration │ │ ├── ComponentFooterConfiguration.java │ │ ├── ComponentHeaderConfiguration.java │ │ ├── AbstractComponentHeaderFooterConfiguration.java │ │ ├── MergedCell.java │ │ ├── ExportExcelConfiguration.java │ │ ├── ExportExcelComponentConfiguration.java │ │ └── ExportExcelSheetConfiguration.java │ │ ├── model │ │ └── ExportType.java │ │ ├── formatter │ │ ├── ColumnFormatter.java │ │ ├── PrefixColumnFormatter.java │ │ ├── SuffixColumnFormatter.java │ │ └── BooleanColumnFormatter.java │ │ ├── function │ │ └── DataCellStyleGeneratorFunction.java │ │ ├── stream │ │ ├── DeletingFileInputStream.java │ │ └── TemporaryFileDownloadResource.java │ │ ├── utils │ │ ├── NameGenerationUtil.java │ │ ├── ExcelStyleUtil.java │ │ └── FormatUtil.java │ │ ├── AbstractExportTo.java │ │ └── ExportToExcel.java ├── assembly │ ├── MANIFEST.MF │ └── assembly.xml └── pom.xml ├── .gitignore ├── pom.xml ├── LICENSE.txt └── README.md /vaadin-excel-exporter-demo/src/main/resources/org/vaadin/addons/README: -------------------------------------------------------------------------------- 1 | Please add your static resources here 2 | -------------------------------------------------------------------------------- /vaadin-excel-exporter-demo/src/main/webapp/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /vaadin-excel-exporter-demo/src/main/webapp/META-INF/context.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /vaadin-excel-exporter-demo/src/main/webapp/VAADIN/themes/demo/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/a-schild/vaadin-excel-exporter/master/vaadin-excel-exporter-demo/src/main/webapp/VAADIN/themes/demo/favicon.ico -------------------------------------------------------------------------------- /vaadin-excel-exporter-demo/src/main/webapp/VAADIN/themes/demo/images/radial-gradient.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/a-schild/vaadin-excel-exporter/master/vaadin-excel-exporter-demo/src/main/webapp/VAADIN/themes/demo/images/radial-gradient.png -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/resources/org/vaadin/addons/public/vaadin-excel-exporter/styles.css: -------------------------------------------------------------------------------- 1 | div.vaadin-excel-exporter-root { 2 | cursor: pointer; 3 | user-select: none; 4 | -webkit-user-select: none; 5 | -moz-user-select: none; 6 | -ms-user-select: none; 7 | } -------------------------------------------------------------------------------- /vaadin-excel-exporter/assembly/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Vaadin-Package-Version: 1 3 | Vaadin-Addon: ${Vaadin-Addon} 4 | Vaadin-License-Title: ${Vaadin-License-Title} 5 | Implementation-Vendor: ${Implementation-Vendor} 6 | Implementation-Title: ${Implementation-Title} 7 | Implementation-Version: ${Implementation-Version} 8 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/resources/org/vaadin/addons/WidgetSet.gwt.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | 14 | styles.scss.cache 15 | rebel.xml 16 | build/ 17 | coverage.ec 18 | /target 19 | target 20 | velocity.log 21 | velocity.log* 22 | src/main/webapp/VAADIN/gwt-unitCache* 23 | */src/main/webapp/VAADIN/widgetsets* 24 | src/main/webapp/VAADIN/widgetsets/* 25 | .classpath 26 | .project 27 | */.settings/ 28 | .settings/org.eclipse.m2e.core.prefs 29 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/configuration/ComponentFooterConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.configuration; 5 | 6 | import net.karneim.pojobuilder.GeneratePojoBuilder; 7 | 8 | import com.vaadin.ui.components.grid.FooterRow; 9 | 10 | /** 11 | * The Class ComponentFooterConfiguration is used to configure headers for the 12 | * Excel component 13 | * 14 | * @author Kartik Suba 15 | */ 16 | @GeneratePojoBuilder(intoPackage = "*.builder") 17 | public class ComponentFooterConfiguration extends AbstractComponentHeaderFooterConfiguration { 18 | 19 | } -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/model/ExportType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.model; 5 | 6 | /** 7 | * The Enum ExportType. 8 | * 9 | * @author Kartik Suba 10 | */ 11 | public enum ExportType { 12 | 13 | /** The xls. */ 14 | XLS("xls"), 15 | 16 | /** The xlsx. */ 17 | XLSX("xlsx"); 18 | 19 | /** The id. */ 20 | private final String extension; 21 | 22 | /** 23 | * Instantiates a new export type. 24 | * 25 | * @param id 26 | * the id 27 | */ 28 | private ExportType(final String extension) { 29 | this.extension = extension; 30 | } 31 | 32 | public String getExtension() { 33 | return this.extension; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/configuration/ComponentHeaderConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.configuration; 5 | 6 | import net.karneim.pojobuilder.GeneratePojoBuilder; 7 | 8 | import com.vaadin.ui.components.grid.HeaderRow; 9 | 10 | /** 11 | * The Class ComponentHeaderConfiguration is used to configure footers for the 12 | * Excel component 13 | * 14 | * @author Kartik Suba 15 | */ 16 | @GeneratePojoBuilder(intoPackage = "*.builder") 17 | public class ComponentHeaderConfiguration extends AbstractComponentHeaderFooterConfiguration { 18 | 19 | private boolean autoFilter = false; 20 | 21 | public boolean isAutoFilter() { 22 | return this.autoFilter; 23 | } 24 | 25 | public void setAutoFilter(boolean autoFilter) { 26 | this.autoFilter = autoFilter; 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/formatter/ColumnFormatter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.formatter; 5 | 6 | import java.io.Serializable; 7 | 8 | /** 9 | * Used to "format columns"; Implement this interface and format the value of a particular column as needed. 10 | * 11 | * @author k.suba 12 | */ 13 | public interface ColumnFormatter extends Serializable { 14 | 15 | /** 16 | * Called by Developer when a cell in a excel column needs to be formatted. 17 | * 18 | * @param value value coming from the model or container 19 | * @param itemId the itemId (aka rowId) for the of the cell to be generated 20 | * @param columnId the id for the generated column (as specified in addGeneratedColumn) 21 | * @return the object 22 | */ 23 | public Object generateCell(Object value, Object itemId, Object columnId); 24 | } 25 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/function/DataCellStyleGeneratorFunction.java: -------------------------------------------------------------------------------- 1 | package org.vaadin.addons.excelexporter.function; 2 | 3 | import org.apache.poi.xssf.usermodel.XSSFCellStyle; 4 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 5 | 6 | /** 7 | * This function helps you to create the cellstyle you want for a specific cell 8 | * via columndId, value and rowNum. 9 | */ 10 | @FunctionalInterface 11 | public interface DataCellStyleGeneratorFunction { 12 | 13 | /** 14 | * Applies this function to the given arguments. 15 | * 16 | * @param workbook 17 | * the workbook 18 | * @param columnId 19 | * the columnId 20 | * @param value 21 | * the value 22 | * @param rowNum 23 | * the rowNum 24 | * @return the function result 25 | */ 26 | XSSFCellStyle apply(XSSFWorkbook workbook, String columnId, Object value, int rowNum); 27 | } -------------------------------------------------------------------------------- /vaadin-excel-exporter-demo/src/main/webapp/VAADIN/themes/demo/styles.scss: -------------------------------------------------------------------------------- 1 | @import "../valo/valo.scss"; 2 | 3 | $gray: #d1d1cf; 4 | $green: #40b527; 5 | $darkgreen: darken($green, 30%); 6 | 7 | // Prefix all selectors in your theme with .demo 8 | .demo { 9 | 10 | // Include valo theme styles in your theme 11 | @include valo; 12 | 13 | // You can style your demo app right here 14 | .demoContentLayout { 15 | background-color: $gray; 16 | background-image: url(images/radial-gradient.png); 17 | background-size: 90%; 18 | background-position: center center; 19 | background-repeat: no-repeat; 20 | } 21 | 22 | // You can also customize your component for the demo 23 | // app, but remember that these styles are not part of 24 | // the component. To include built-in CSS for your component, 25 | // edit client/styles.css under java sources 26 | div.vaadin-excel-exporter-root { 27 | color: $green; 28 | font-size: 50pt; 29 | font-weight: bold; 30 | text-shadow: 0px 3px 0px $darkgreen, 31 | 0px 14px 10px rgba(0,0,0,0.15), 32 | 0px 24px 2px rgba(0,0,0,0.1), 33 | 0px 34px 30px rgba(0,0,0,0.1); 34 | text-align: center; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/stream/DeletingFileInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.stream; 5 | 6 | import java.io.File; 7 | import java.io.FileInputStream; 8 | import java.io.FileNotFoundException; 9 | import java.io.IOException; 10 | 11 | /** 12 | * This input stream deletes the given file when the InputStream is closed; intended to be used with temporary files. 13 | * 14 | * Code obtained from: http://vaadin.com/forum/-/message_boards/view_message/159583 15 | * 16 | * @author Kartik Suba 17 | */ 18 | 19 | class DeletingFileInputStream extends FileInputStream { 20 | 21 | /** The file. */ 22 | protected File file = null; 23 | 24 | /** 25 | * Instantiates a new deleting file input stream. 26 | * 27 | * @param file the file 28 | * @throws FileNotFoundException the file not found exception 29 | */ 30 | public DeletingFileInputStream(final File file) throws FileNotFoundException { 31 | super(file); 32 | this.file = file; 33 | } 34 | 35 | /* 36 | * (non-Javadoc) 37 | * @see java.io.FileInputStream#close() 38 | */ 39 | @Override 40 | public void close() throws IOException { 41 | super.close(); 42 | this.file.delete(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/assembly/assembly.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | addon 7 | 8 | 10 | 11 | 12 | zip 13 | 14 | 15 | 16 | false 17 | 18 | 19 | 20 | .. 21 | 22 | LICENSE.txt 23 | README.md 24 | 25 | 26 | 27 | target 28 | 29 | 30 | *.jar 31 | *.pdf 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | assembly/MANIFEST.MF 40 | META-INF 41 | true 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/configuration/AbstractComponentHeaderFooterConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.configuration; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * The Class ComponentHeaderConfiguration is used to configure footers for the 10 | * Excel component 11 | * 12 | * @author Kartik Suba 13 | */ 14 | public abstract class AbstractComponentHeaderFooterConfiguration { 15 | 16 | /** The row. */ 17 | private ROWTYPE row; 18 | 19 | /** The column keys. */ 20 | private String[] columnKeys; 21 | 22 | /** The merged cells. */ 23 | private List mergedCells; 24 | 25 | /** The is default. */ 26 | private Boolean defaultConfig; 27 | 28 | public ROWTYPE getRow() { 29 | return this.row; 30 | } 31 | 32 | public void setRow(ROWTYPE row) { 33 | this.row = row; 34 | } 35 | 36 | public String[] getColumnKeys() { 37 | return this.columnKeys; 38 | } 39 | 40 | public void setColumnKeys(String[] columnKeys) { 41 | this.columnKeys = columnKeys; 42 | } 43 | 44 | public List getMergedCells() { 45 | return this.mergedCells; 46 | } 47 | 48 | public void setMergedCells(List mergedCells) { 49 | this.mergedCells = mergedCells; 50 | } 51 | 52 | public Boolean getDefaultConfig() { 53 | return this.defaultConfig; 54 | } 55 | 56 | public void setDefaultConfig(Boolean defaultConfig) { 57 | this.defaultConfig = defaultConfig; 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/formatter/PrefixColumnFormatter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.formatter; 5 | 6 | /** 7 | * The Class PrefixColumnFormatter is used to attach configured prefix to the bean value 8 | * 9 | * @author k.suba 10 | */ 11 | /** 12 | * Used to "format columns with Prefix"; Implement this interface and format the 13 | * value by adding a prefix.. as needed. 14 | * 15 | */ 16 | public class PrefixColumnFormatter implements ColumnFormatter { 17 | 18 | /** The Constant serialVersionUID. */ 19 | private static final long serialVersionUID = -1799235402794402089L; 20 | 21 | /** The prefix. */ 22 | private String prefix; 23 | 24 | /** 25 | * Instantiates a new prefix column formatter. 26 | * 27 | * @param prefix 28 | * the prefix 29 | */ 30 | public PrefixColumnFormatter(final String prefix) { 31 | this.prefix = prefix; 32 | } 33 | 34 | /** 35 | * Called by Developer when a cell in a excel column needs to be formatted. 36 | * 37 | * @param value 38 | * value coming from the model or container 39 | * @param itemId 40 | * the itemId (aka rowId) for the of the cell to be generated 41 | * @param columnId 42 | * the id for the generated column (as specified in 43 | * addGeneratedColumn) 44 | * @return the object 45 | */ 46 | @Override 47 | public Object generateCell(final Object value, final Object itemId, final Object columnId) { 48 | if (value == null) { 49 | return ""; 50 | } 51 | 52 | if (!(value instanceof String)) { 53 | return "Not convertable to string value"; 54 | } 55 | 56 | return this.prefix + " " + (String) value; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/formatter/SuffixColumnFormatter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.formatter; 5 | 6 | /** 7 | * The Class SuffixColumnFormatter is used to attach configured suffix to the bean value 8 | * 9 | * @author k.suba 10 | */ 11 | /** 12 | * Used to "format columns with Suffix"; Implement this interface and format the 13 | * value by adding a suffix like %, $, kg etc.. as needed. 14 | * 15 | */ 16 | public class SuffixColumnFormatter implements ColumnFormatter { 17 | 18 | /** The Constant serialVersionUID. */ 19 | private static final long serialVersionUID = -4124097204858705984L; 20 | 21 | /** The suffix. */ 22 | private String suffix; 23 | 24 | /** 25 | * Instantiates a new suffix column formatter. 26 | * 27 | * @param suffix 28 | * the suffix 29 | */ 30 | public SuffixColumnFormatter(final String suffix) { 31 | this.suffix = suffix; 32 | } 33 | 34 | /** 35 | * Called by Developer when a cell in a excel column needs to be formatted. 36 | * 37 | * @param value 38 | * value coming from the model or container 39 | * @param itemId 40 | * the itemId (aka rowId) for the of the cell to be generated 41 | * @param columnId 42 | * the id for the generated column (as specified in 43 | * addGeneratedColumn) 44 | * @return the object 45 | */ 46 | @Override 47 | public Object generateCell(final Object value, final Object itemId, final Object columnId) { 48 | if (value == null) { 49 | return ""; 50 | } 51 | 52 | if (!(value instanceof String)) { 53 | return "Not convertable to string value"; 54 | } 55 | 56 | return (String) value + " " + this.suffix; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/configuration/MergedCell.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.configuration; 5 | 6 | import net.karneim.pojobuilder.GeneratePojoBuilder; 7 | 8 | // TODO: Auto-generated Javadoc 9 | /** 10 | * The Class MergedCell. 11 | * 12 | * @author Kartik Suba 13 | */ 14 | @GeneratePojoBuilder(intoPackage = "*.builder") 15 | public class MergedCell { 16 | 17 | /** The start property. */ 18 | private String startProperty; 19 | 20 | /** The end property. */ 21 | private String endProperty; 22 | 23 | /** The header key. */ 24 | private String headerKey; 25 | 26 | /** 27 | * Gets the start property. 28 | * 29 | * @return the start property 30 | */ 31 | public String getStartProperty() { 32 | return this.startProperty; 33 | } 34 | 35 | /** 36 | * Sets the start property. 37 | * 38 | * @param startProperty 39 | * the new start property 40 | */ 41 | public void setStartProperty(final String startProperty) { 42 | this.startProperty = startProperty; 43 | } 44 | 45 | /** 46 | * Gets the end property. 47 | * 48 | * @return the end property 49 | */ 50 | public String getEndProperty() { 51 | return this.endProperty; 52 | } 53 | 54 | /** 55 | * Sets the end property. 56 | * 57 | * @param endProperty 58 | * the new end property 59 | */ 60 | public void setEndProperty(final String endProperty) { 61 | this.endProperty = endProperty; 62 | } 63 | 64 | /** 65 | * Gets the header key. 66 | * 67 | * @return the header key 68 | */ 69 | public String getHeaderKey() { 70 | return this.headerKey; 71 | } 72 | 73 | /** 74 | * Sets the header key. 75 | * 76 | * @param headerKey 77 | * the new header key 78 | */ 79 | public void setHeaderKey(final String headerKey) { 80 | this.headerKey = headerKey; 81 | } 82 | } -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/formatter/BooleanColumnFormatter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.formatter; 5 | 6 | /** 7 | * Used to "format Boolean columns"; Implement this interface and format the 8 | * Boolean value with values such as Yes/No, True/False, Active/Not-Active etc.. 9 | * as needed. 10 | * 11 | * @author k.suba 12 | */ 13 | public class BooleanColumnFormatter implements ColumnFormatter { 14 | 15 | /** The Constant serialVersionUID. */ 16 | private static final long serialVersionUID = -8041702795081968899L; 17 | 18 | /** Placeholder string when the value are true or false */ 19 | private String truePlaceholder; 20 | private String falsePlaceholder; 21 | 22 | /** 23 | * Instantiates a new boolean column formatter. 24 | * 25 | * @param truePlaceholder 26 | * the true value 27 | * @param falsePlaceholder 28 | * the false value 29 | */ 30 | public BooleanColumnFormatter(final String truePlaceholder, final String falsePlaceholder) { 31 | this.truePlaceholder = truePlaceholder; 32 | this.falsePlaceholder = falsePlaceholder; 33 | } 34 | 35 | /** 36 | * Called by Developer when a cell in a excel column needs to be formatted. 37 | * 38 | * @param value 39 | * value coming from the model or container 40 | * @param itemId 41 | * the itemId (aka rowId) for the of the cell to be generated 42 | * @param columnId 43 | * the id for the generated column (as specified in 44 | * addGeneratedColumn) 45 | * @return the object 46 | */ 47 | @Override 48 | public Object generateCell(final Object value, final Object itemId, final Object columnId) { 49 | if (value == null) { 50 | return ""; 51 | } 52 | 53 | if (!(value instanceof Boolean)) { 54 | return "Not convertable to boolean value"; 55 | } 56 | 57 | Boolean bool = (Boolean) value; 58 | 59 | return bool ? this.truePlaceholder : this.falsePlaceholder; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/utils/NameGenerationUtil.java: -------------------------------------------------------------------------------- 1 | package org.vaadin.addons.excelexporter.utils; 2 | 3 | import java.util.Calendar; 4 | import org.vaadin.addons.excelexporter.model.ExportType; 5 | 6 | public class NameGenerationUtil { 7 | 8 | private static final String DEFAULT_FILENAME = "Export"; 9 | private final static String DEFAULT_REPORTTITLE = "Report"; 10 | private static final String DEFAULT_SHEETNAME = "Sheet"; 11 | 12 | private NameGenerationUtil() { 13 | 14 | } 15 | 16 | public static String getFilename(final String filename, int maxFilenameCalendarExtension, ExportType exportType) { 17 | String result = filename; 18 | if (result == null || result.isEmpty()) { 19 | result = DEFAULT_FILENAME; 20 | } 21 | 22 | Calendar calendar = Calendar.getInstance(); 23 | 24 | String dateTimeExtension = ""; 25 | switch (maxFilenameCalendarExtension) { 26 | case Calendar.SECOND: 27 | dateTimeExtension = "_" + calendar.get(Calendar.SECOND) + dateTimeExtension; 28 | case Calendar.MINUTE: 29 | dateTimeExtension = "_" + calendar.get(Calendar.MINUTE) + dateTimeExtension; 30 | case Calendar.HOUR: 31 | dateTimeExtension = "_" + calendar.get(Calendar.HOUR) + dateTimeExtension; 32 | case Calendar.DATE: 33 | dateTimeExtension = "_" + (calendar.get(Calendar.MONTH) + 1) + dateTimeExtension; 34 | case Calendar.MONTH: 35 | dateTimeExtension = "_" + calendar.get(Calendar.MONTH) + dateTimeExtension; 36 | case Calendar.YEAR: 37 | dateTimeExtension = "_" + calendar.get(Calendar.YEAR) + dateTimeExtension; 38 | default: 39 | break; 40 | } 41 | 42 | result += dateTimeExtension; 43 | 44 | result += "." + exportType.getExtension(); 45 | return result; 46 | } 47 | 48 | public static String getSheetname(String sheetname, int index) { 49 | if (sheetname == null || sheetname.isEmpty()) { 50 | return DEFAULT_SHEETNAME + index; 51 | } 52 | 53 | return sheetname; 54 | } 55 | 56 | public static String getReportTitle(String reportTitle, int index) { 57 | if (reportTitle == null || reportTitle.isEmpty()) { 58 | return DEFAULT_REPORTTITLE + ": " + index; 59 | } 60 | 61 | return reportTitle; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /vaadin-excel-exporter-demo/src/main/java/org/vaadin/addons/excelexporter/demo/data/DataModelGenerator.java: -------------------------------------------------------------------------------- 1 | package org.vaadin.addons.excelexporter.demo.data; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.Random; 6 | 7 | import org.vaadin.addons.excelexporter.demo.DataModel; 8 | 9 | public class DataModelGenerator { 10 | 11 | private DataModelGenerator() { 12 | } 13 | 14 | private static final String[] CATALOGUES = { "ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VWX", "YZ" }; 15 | private static final String[] COUNTRIES = { "India", "Germany", "America", "Italy", "Spain", "Portugal" }; 16 | private static final String[] PRODUCTTYPES = { "Car", "Motorcycle", "Bicycle" }; 17 | private static final String[] COMPANIES = { "Audi", "VW", "Fiat", "Lexus", "Suzuki" }; 18 | private static final String[] QUALITYTYPES = { "Luxury", "Premium", "Sports", "Racing", "Standard" }; 19 | 20 | public static Collection generate(int cnt) { 21 | 22 | ArrayList result = new ArrayList<>(); 23 | for (int i = 1; i <= cnt; i++) { 24 | result.add(getDataModel(CATALOGUES[new Random().nextInt(CATALOGUES.length)], 25 | COUNTRIES[new Random().nextInt(COUNTRIES.length)], 26 | PRODUCTTYPES[new Random().nextInt(PRODUCTTYPES.length)], 27 | COMPANIES[new Random().nextInt(COMPANIES.length)], new Random().nextInt() + "$", 28 | "contractor" + i, new Random().nextDouble(), new Random().nextDouble(), 29 | new Random().nextBoolean(), new Random().nextInt(), 30 | QUALITYTYPES[new Random().nextInt(QUALITYTYPES.length)])); 31 | } 32 | 33 | return result; 34 | } 35 | 36 | private static DataModel getDataModel(String catalogue, String country, String productType, String plannedPrinter, 37 | String cheapest, String contractor, Double totalCosts, Double differenceToMin, Boolean active, 38 | Integer counter, String comment) { 39 | DataModel dataModel = new DataModel(); 40 | dataModel.setCatalogue(catalogue); 41 | dataModel.setCountry(country); 42 | dataModel.setProductType(productType); 43 | dataModel.setPlannedPrinter(plannedPrinter); 44 | dataModel.setCheapest(cheapest); 45 | dataModel.setContractor(contractor); 46 | dataModel.setTotalCosts(totalCosts); 47 | dataModel.setDifferenceToMin(differenceToMin); 48 | dataModel.setActive(active); 49 | dataModel.setCounter(counter); 50 | dataModel.setComment(comment); 51 | return dataModel; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/AbstractExportTo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter; 5 | 6 | import java.io.File; 7 | import java.io.FileNotFoundException; 8 | import java.util.logging.Logger; 9 | 10 | import org.vaadin.addons.excelexporter.stream.TemporaryFileDownloadResource; 11 | 12 | import com.vaadin.ui.UI; 13 | 14 | /** 15 | * The Class ExportUtility is the abstract class that defines the structure of 16 | * the utility 17 | * 18 | * @author Kartik Suba 19 | */ 20 | public abstract class AbstractExportTo { 21 | 22 | /** The Constant LOGGER. */ 23 | protected static final Logger LOGGER = Logger.getLogger(AbstractExportTo.class.getName()); 24 | 25 | protected final String mimeType; 26 | 27 | public AbstractExportTo(String mimeType) { 28 | this.mimeType = mimeType; 29 | } 30 | 31 | /** 32 | * Send converted. 33 | * 34 | * @param file 35 | * 36 | * @return true, if successful 37 | */ 38 | protected abstract boolean sendConverted(File file); 39 | 40 | /** 41 | * Generate report file. 42 | * 43 | * @return the file 44 | */ 45 | protected abstract File generateReportFile(); 46 | 47 | /** 48 | * Create and export the Table contents as some sort of file type. In the 49 | * case of conversion to Excel it would be an ".xls" file containing the 50 | * contents as a report. Only the export() method needs to be called. If the 51 | * user wishes to manipulate the converted object to export, then 52 | * convertTable() should be called separately, and, after manipulation, 53 | * sendConverted(). 54 | */ 55 | 56 | public void export() { 57 | File file = generateReportFile(); 58 | if (file != null) { 59 | sendConverted(file); 60 | } 61 | } 62 | 63 | /** 64 | * Send converted file to user. 65 | * 66 | * @param fileToExport 67 | * the file to export 68 | * @param exportFileName 69 | * the export file name 70 | * @return true, if successful 71 | */ 72 | @SuppressWarnings("deprecation") 73 | protected boolean sendConvertedFileToUser(final File fileToExport, final String exportFileName) { 74 | UI ui = UI.getCurrent(); 75 | TemporaryFileDownloadResource resource; 76 | try { 77 | resource = new TemporaryFileDownloadResource(ui, exportFileName, this.mimeType, fileToExport); 78 | ui.getPage() 79 | .open(resource, null, false); 80 | } catch (final FileNotFoundException e) { 81 | LOGGER.warning("Sending file to user failed with FileNotFoundException " + e); 82 | 83 | return false; 84 | } 85 | 86 | return true; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | org.vaadin.addons 6 | vaadin-excel-exporter-root 7 | pom 8 | 2.1-SNAPSHOT 9 | Excel Exporter Root 10 | 11 | 12 | 3 13 | 14 | 15 | 16 | vaadin-excel-exporter 17 | vaadin-excel-exporter-demo 18 | 19 | 20 | 21 | 22 | Kartik Suba 23 | k.suba@direction.biz or kartiksuba.creations@gmail.com 24 | Direction Software Solutions 25 | http://www.direction.biz 26 | 27 | 28 | 29 | 30 | 31 | The MIT License (MIT) 32 | http://opensource.org/licenses/MIT 33 | 34 | 35 | 36 | 37 | git://github.com/bonprix/vaadin-excel-exporter.git 38 | scm:git:git://github.com/bonprix/vaadin-excel-exporter.git 39 | scm:git:https://github.com/bonprix/vaadin-excel-exporter.git 40 | 41 | 42 | 43 | 44 | 45 | vaadin-prerelease 46 | 47 | false 48 | 49 | 50 | 51 | 52 | vaadin-prereleases 53 | http://maven.vaadin.com/vaadin-prereleases 54 | 55 | 56 | vaadin-snapshots 57 | https://oss.sonatype.org/content/repositories/vaadin-snapshots/ 58 | 59 | false 60 | 61 | 62 | true 63 | 64 | 65 | 66 | 67 | 68 | vaadin-prereleases 69 | http://maven.vaadin.com/vaadin-prereleases 70 | 71 | 72 | vaadin-snapshots 73 | https://oss.sonatype.org/content/repositories/vaadin-snapshots/ 74 | 75 | false 76 | 77 | 78 | true 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/configuration/ExportExcelConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.configuration; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Calendar; 8 | import java.util.List; 9 | 10 | import net.karneim.pojobuilder.GeneratePojoBuilder; 11 | 12 | /** 13 | * The Class ExportExcelConfiguration is used to configure the Excel Worksheet. 14 | * The filename, extension, generatedBy, and sheet configurations can also be 15 | * configured. 16 | * 17 | * @author Kartik Suba 18 | */ 19 | @GeneratePojoBuilder(intoPackage = "*.builder") 20 | public class ExportExcelConfiguration { 21 | 22 | /** The export file name. */ 23 | private String exportFileName; 24 | 25 | /** The generated by. */ 26 | private String generatedBy; 27 | 28 | /** The sheet configs. */ 29 | private List> sheetConfigs = new ArrayList<>(); 30 | 31 | /** 32 | * The DateTime that should be added to the filename (use Calendar.YEAR etc 33 | * for example) 34 | */ 35 | private int maxFilenameCalendarExtension = Calendar.MINUTE; 36 | 37 | /** 38 | * Gets the export file name. 39 | * 40 | * @return the export file name 41 | */ 42 | public String getExportFileName() { 43 | return this.exportFileName; 44 | } 45 | 46 | /** 47 | * Gets the generated by. 48 | * 49 | * @return the generated by 50 | */ 51 | public String getGeneratedBy() { 52 | return this.generatedBy; 53 | } 54 | 55 | /** 56 | * Sets the export file name. 57 | * 58 | * @param exportFileName 59 | * the new export file name 60 | */ 61 | public void setExportFileName(final String exportFileName) { 62 | this.exportFileName = exportFileName; 63 | } 64 | 65 | /** 66 | * Sets the generated by. 67 | * 68 | * @param generatedBy 69 | * the new generated by 70 | */ 71 | public void setGeneratedBy(final String generatedBy) { 72 | this.generatedBy = generatedBy; 73 | } 74 | 75 | /** 76 | * Gets the sheet configs. 77 | * 78 | * @return the sheet configs 79 | */ 80 | public List> getSheetConfigs() { 81 | return this.sheetConfigs; 82 | } 83 | 84 | /** 85 | * Sets the sheet configs. 86 | * 87 | * @param sheetConfigs 88 | * the new sheet configs 89 | */ 90 | public void setSheetConfigs(final List> sheetConfigs) { 91 | this.sheetConfigs = sheetConfigs; 92 | for (ExportExcelSheetConfiguration sheetConfig : sheetConfigs) { 93 | sheetConfig.setExportExcelConfiguration(this); 94 | } 95 | } 96 | 97 | public int getMaxFilenameCalendarExtension() { 98 | return this.maxFilenameCalendarExtension; 99 | } 100 | 101 | public void setMaxFilenameCalendarExtension(int maxFilenameCalendarExtension) { 102 | this.maxFilenameCalendarExtension = maxFilenameCalendarExtension; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/stream/TemporaryFileDownloadResource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.stream; 5 | 6 | import java.io.File; 7 | import java.io.FileNotFoundException; 8 | import java.io.InputStream; 9 | 10 | import com.vaadin.server.DownloadStream; 11 | import com.vaadin.server.StreamResource; 12 | import com.vaadin.ui.UI; 13 | 14 | /** 15 | * The Class TemporaryFileDownloadResource. 16 | * 17 | * Code obtained from: 18 | * http://vaadin.com/forum/-/message_boards/view_message/159583 19 | * 20 | * @author Kartik Suba 21 | * 22 | */ 23 | public class TemporaryFileDownloadResource extends StreamResource { 24 | 25 | /** The Constant serialVersionUID. */ 26 | private static final long serialVersionUID = 476307190141362413L; 27 | 28 | /** The filename. */ 29 | private final String filename; 30 | 31 | /** The content type. */ 32 | private final String contentType; 33 | 34 | /** 35 | * Instantiates a new temporary file download resource. 36 | * 37 | * @param application 38 | * the application 39 | * @param fileName 40 | * the file name 41 | * @param contentType 42 | * the content type 43 | * @param tempFile 44 | * the temp file 45 | * @throws FileNotFoundException 46 | * the file not found exception 47 | */ 48 | public TemporaryFileDownloadResource(final UI application, final String fileName, final String contentType, 49 | final File tempFile) throws FileNotFoundException { 50 | super(new FileStreamResource(tempFile), fileName); 51 | this.filename = fileName; 52 | this.contentType = contentType; 53 | } 54 | 55 | /** 56 | * Gets the stream. 57 | * 58 | * @return the stream 59 | */ 60 | /* 61 | * (non-Javadoc) 62 | * 63 | * @see com.vaadin.terminal.StreamResource#getStream() 64 | */ 65 | @Override 66 | public DownloadStream getStream() { 67 | final DownloadStream stream = new DownloadStream(getStreamSource().getStream(), this.contentType, 68 | this.filename); 69 | stream.setParameter("Content-Disposition", "attachment;filename=" + this.filename); 70 | // This magic incantation should prevent anyone from caching the data 71 | stream.setParameter("Cache-Control", "private,no-cache,no-store"); 72 | // In theory <=0 disables caching. In practice Chrome, Safari (and, 73 | // apparently, IE) all 74 | // ignore <=0. Set to 1s 75 | stream.setCacheTime(1000); 76 | 77 | return stream; 78 | } 79 | 80 | /** 81 | * The Class FileStreamResource. 82 | */ 83 | private static class FileStreamResource implements StreamResource.StreamSource { 84 | 85 | /** The Constant serialVersionUID. */ 86 | private static final long serialVersionUID = 3801605481686085335L; 87 | 88 | /** The input stream. */ 89 | private final InputStream inputStream; 90 | 91 | /** 92 | * Instantiates a new file stream resource. 93 | * 94 | * @param fileToDownload 95 | * the file to download 96 | * @throws FileNotFoundException 97 | * the file not found exception 98 | */ 99 | public FileStreamResource(final File fileToDownload) throws FileNotFoundException { 100 | this.inputStream = new DeletingFileInputStream(fileToDownload); 101 | } 102 | 103 | /** 104 | * Gets the stream. 105 | * 106 | * @return the stream 107 | */ 108 | /* 109 | * (non-Javadoc) 110 | * 111 | * @see com.vaadin.terminal.StreamResource.StreamSource#getStream() 112 | */ 113 | @Override 114 | public InputStream getStream() { 115 | return this.inputStream; 116 | } 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/utils/ExcelStyleUtil.java: -------------------------------------------------------------------------------- 1 | package org.vaadin.addons.excelexporter.utils; 2 | 3 | import java.awt.Color; 4 | import org.apache.poi.ss.usermodel.BorderStyle; 5 | import org.apache.poi.ss.usermodel.Cell; 6 | import org.apache.poi.xssf.usermodel.XSSFCellStyle; 7 | import org.apache.poi.xssf.usermodel.XSSFColor; 8 | import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide; 9 | 10 | import com.vaadin.shared.ui.grid.GridStaticCellType; 11 | import com.vaadin.ui.components.grid.FooterCell; 12 | import com.vaadin.ui.components.grid.HeaderCell; 13 | 14 | public class ExcelStyleUtil { 15 | 16 | private ExcelStyleUtil() { 17 | 18 | } 19 | 20 | /** 21 | * Sets the borders. 22 | * 23 | * @param headerCellStyle 24 | * the header cell style 25 | * @param left 26 | * the left 27 | * @param right 28 | * the right 29 | * @param top 30 | * the top 31 | * @param bottom 32 | * the bottom 33 | * @param color 34 | * the color 35 | * @return the XSSF cell style 36 | */ 37 | public static XSSFCellStyle setBorders(final XSSFCellStyle headerCellStyle, final Boolean left, final Boolean right, 38 | final Boolean top, final Boolean bottom, final Color color) { 39 | if (bottom) { 40 | headerCellStyle.setBorderBottom(BorderStyle.THIN); 41 | headerCellStyle.setBorderColor(BorderSide.BOTTOM, new XSSFColor(color)); 42 | } 43 | 44 | if (top) { 45 | headerCellStyle.setBorderTop(BorderStyle.THIN); 46 | headerCellStyle.setBorderColor(BorderSide.TOP, new XSSFColor(color)); 47 | } 48 | 49 | if (left) { 50 | headerCellStyle.setBorderLeft(BorderStyle.THIN); 51 | headerCellStyle.setBorderColor(BorderSide.LEFT, new XSSFColor(color)); 52 | } 53 | 54 | if (right) { 55 | headerCellStyle.setBorderRight(BorderStyle.THIN); 56 | headerCellStyle.setBorderColor(BorderSide.RIGHT, new XSSFColor(color)); 57 | } 58 | 59 | return headerCellStyle; 60 | } 61 | 62 | /** 63 | * Adds the generic grid header row configured in the header configs 64 | * 65 | * @param gridHeaderCell 66 | * the grid header cell 67 | * @param myCell 68 | * the my cell 69 | */ 70 | public static void addGenericGridHeaderRow(final HeaderCell gridHeaderCell, final Cell myCell) { 71 | 72 | if (gridHeaderCell.getCellType() 73 | .equals(GridStaticCellType.TEXT)) { 74 | myCell.setCellValue(gridHeaderCell.getText()); 75 | } else if (gridHeaderCell.getCellType() 76 | .equals(GridStaticCellType.HTML)) { 77 | myCell.setCellValue(gridHeaderCell.getHtml()); 78 | } else if (gridHeaderCell.getCellType() 79 | .equals(GridStaticCellType.WIDGET)) { 80 | myCell.setCellValue(gridHeaderCell.getComponent() 81 | .toString()); 82 | } 83 | } 84 | 85 | /** 86 | * Adds the generic grid footer row configured in the footer configs 87 | * 88 | * @param gridHeaderCell 89 | * the grid header cell 90 | * @param myCell 91 | * the my cell 92 | */ 93 | public static void addGenericGridFooterRow(final FooterCell gridHeaderCell, final Cell myCell) { 94 | 95 | if (gridHeaderCell.getCellType() 96 | .equals(GridStaticCellType.TEXT)) { 97 | myCell.setCellValue(gridHeaderCell.getText()); 98 | } else if (gridHeaderCell.getCellType() 99 | .equals(GridStaticCellType.HTML)) { 100 | myCell.setCellValue(gridHeaderCell.getHtml()); 101 | } else if (gridHeaderCell.getCellType() 102 | .equals(GridStaticCellType.WIDGET)) { 103 | myCell.setCellValue(gridHeaderCell.getComponent() 104 | .toString()); 105 | } 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/utils/FormatUtil.java: -------------------------------------------------------------------------------- 1 | package org.vaadin.addons.excelexporter.utils; 2 | 3 | import java.math.BigDecimal; 4 | import java.text.DateFormat; 5 | import java.text.NumberFormat; 6 | import java.text.SimpleDateFormat; 7 | import java.util.Date; 8 | import java.util.Locale; 9 | 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import org.vaadin.addons.excelexporter.configuration.ExportExcelComponentConfiguration; 13 | import com.vaadin.ui.UI; 14 | 15 | public class FormatUtil { 16 | 17 | /** The Constant LOGGER. */ 18 | private static final Logger LOGGER = LoggerFactory.getLogger(ExcelStyleUtil.class); 19 | 20 | private FormatUtil() { 21 | 22 | } 23 | 24 | /************************************ 25 | * Styles and Designing of Excel Content 26 | *******************************************/ 27 | 28 | /** 29 | * Formats Date based on the UI's locale 30 | * 31 | * @param val 32 | * the val 33 | * @param datePattern 34 | * the pattern 35 | * @return the string 36 | */ 37 | public static String formatDate(final Date val, String datePattern) { 38 | if (val == null) { 39 | return null; 40 | } 41 | DateFormat df = new SimpleDateFormat(datePattern, UI.getCurrent() 42 | .getLocale()); 43 | return df.format(val); 44 | } 45 | 46 | /** 47 | * Localized format for Integer and BigDecimal values 48 | * 49 | * @param value 50 | * the value 51 | * @param isIntOrBigD 52 | * the is int or big D 53 | * @return the string 54 | */ 55 | public static String localizedFormat(final String value, final Boolean isIntOrBigD) { 56 | Locale loc = UI.getCurrent() 57 | .getLocale(); 58 | if (isIntOrBigD) { 59 | Integer modifiedValue = unLocalizedFormatForInt(value); 60 | 61 | NumberFormat nf = NumberFormat.getNumberInstance(loc); 62 | nf.setParseIntegerOnly(true); 63 | return nf.format(modifiedValue); 64 | } else { 65 | BigDecimal modifiedValue = unLocalizedFormatForBigDecimal(value); 66 | NumberFormat nf = NumberFormat.getNumberInstance(loc); 67 | nf.setMinimumFractionDigits(2); 68 | nf.setMaximumFractionDigits(2); 69 | return nf.format(modifiedValue); 70 | } 71 | 72 | } 73 | 74 | /** 75 | * Format float. 76 | * 77 | * @param value 78 | * the value 79 | * @return the string 80 | */ 81 | public static String formatFloat(final Double value) { 82 | Locale loc = UI.getCurrent() 83 | .getLocale(); 84 | NumberFormat nf = NumberFormat.getNumberInstance(loc); 85 | nf.setMinimumFractionDigits(2); 86 | nf.setMaximumFractionDigits(2); 87 | return nf.format(value); 88 | } 89 | 90 | /** 91 | * Un localized format for int. 92 | * 93 | * @param value 94 | * the value 95 | * @return the integer 96 | */ 97 | private static Integer unLocalizedFormatForInt(final String value) { 98 | Locale loc = UI.getCurrent() 99 | .getLocale(); 100 | Integer modifiedValue = 0; 101 | 102 | if (value != null && !value.contains(".") && !value.contains(",")) { 103 | modifiedValue = Integer.valueOf(value); 104 | } else { 105 | if (value != null && "en".equals(loc.getLanguage())) { 106 | modifiedValue = Integer.valueOf(value.replaceAll(",", "")); 107 | } else if (value != null && "de".equals(loc.getLanguage())) { 108 | modifiedValue = Integer.valueOf(value.replaceAll("\\.", "")); 109 | } 110 | } 111 | return modifiedValue; 112 | } 113 | 114 | /** 115 | * Un localized format for big decimal. 116 | * 117 | * @param value 118 | * the value 119 | * @return the big decimal 120 | */ 121 | private static BigDecimal unLocalizedFormatForBigDecimal(final String value) { 122 | Locale loc = UI.getCurrent() 123 | .getLocale(); 124 | BigDecimal modifiedValue = new BigDecimal(Double.valueOf("0")); 125 | 126 | if (value != null && !value.contains(".") && !value.contains(",")) { 127 | 128 | modifiedValue = BigDecimal.valueOf(Double.valueOf(value)); 129 | } else { 130 | if (value != null && "en".equals(loc.getLanguage())) { 131 | 132 | modifiedValue = BigDecimal.valueOf(Double.valueOf(value.replaceAll(",", ""))); 133 | } else if (value != null && "de".equals(loc.getLanguage())) { 134 | 135 | String temp = value; 136 | if (value.contains(".")) { 137 | temp = value.replaceAll("\\.", ""); 138 | 139 | } 140 | if (temp.contains(",")) { 141 | temp = temp.replaceAll(",", "\\."); 142 | 143 | } 144 | modifiedValue = BigDecimal.valueOf(Double.valueOf(temp)); 145 | } 146 | } 147 | return modifiedValue; 148 | } 149 | 150 | /** 151 | * Apply column formatter. 152 | * 153 | * @param visibleColumns 154 | * the visible columns 155 | * @param componentConfiguration 156 | * the component configuration 157 | * @param itemId 158 | * the item id 159 | * @param columns 160 | * the columns 161 | * @param value 162 | * the value 163 | * @return the string 164 | */ 165 | public static String applyColumnFormatter(final Object[] visibleColumns, 166 | final ExportExcelComponentConfiguration componentConfiguration, final BEANTYPE itemId, 167 | final int columns, final Object value) { 168 | String formatted = null; 169 | if (componentConfiguration.getColumnFormatter(visibleColumns[columns]) != null) { 170 | try { 171 | formatted = (String) componentConfiguration.getColumnFormatter(visibleColumns[columns]) 172 | .generateCell(value, itemId, visibleColumns[columns]); 173 | } catch (Exception e) { 174 | LOGGER.info("Formatting failed", e); 175 | } 176 | } 177 | return formatted; 178 | } 179 | 180 | } 181 | -------------------------------------------------------------------------------- /vaadin-excel-exporter-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | org.vaadin.addons 5 | vaadin-excel-exporter-demo 6 | war 7 | 2.1-SNAPSHOT 8 | Excel Exporter Demo 9 | 10 | 11 | 3 12 | 13 | 14 | 15 | UTF-8 16 | 1.8 17 | 1.8 18 | 8.4.3 19 | ${vaadin.version} 20 | 9.2.3.v20140905 21 | 22 | 23 | 24 | Kartik Suba (Direction Software Solutions) 25 | https://github.com/bonprix/vaadin-excel-exporter 26 | 27 | 28 | 29 | git://github.com/bonprix/vaadin-excel-exporter.git 30 | scm:git:git://github.com/bonprix/vaadin-excel-exporter.git 31 | scm:git:ssh://git@github.com:/bonprix/vaadin-excel-exporter.git 32 | 33 | 34 | 35 | GitHub 36 | https://github.com/bonprix/vaadin-excel-exporter/issues 37 | 38 | 39 | 40 | 41 | Apache 2 42 | http://www.apache.org/licenses/LICENSE-2.0.txt 43 | repo 44 | 45 | 46 | 47 | 48 | 49 | vaadin-addons 50 | http://maven.vaadin.com/vaadin-addons 51 | 52 | 53 | vaadin-snapshots 54 | https://oss.sonatype.org/content/repositories/vaadin-snapshots/ 55 | 56 | false 57 | 58 | 59 | true 60 | 61 | 62 | 63 | 64 | 65 | 66 | vaadin-snapshots 67 | https://oss.sonatype.org/content/repositories/vaadin-snapshots/ 68 | 69 | false 70 | 71 | 72 | true 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | com.vaadin 81 | vaadin-bom 82 | ${vaadin.version} 83 | pom 84 | import 85 | 86 | 87 | 88 | 89 | 90 | 91 | org.vaadin.addons 92 | vaadin-excel-exporter 93 | ${project.version} 94 | 95 | 96 | com.vaadin 97 | vaadin-push 98 | 99 | 100 | com.vaadin 101 | vaadin-client-compiler 102 | provided 103 | 104 | 105 | com.vaadin 106 | vaadin-themes 107 | 108 | 109 | javax.servlet 110 | javax.servlet-api 111 | 3.0.1 112 | provided 113 | 114 | 115 | 116 | 117 | 118 | 119 | maven-war-plugin 120 | 3.0.0 121 | 122 | false 123 | 124 | 125 | 126 | 127 | com.vaadin 128 | vaadin-maven-plugin 129 | ${vaadin.plugin.version} 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | resources 138 | update-widgetset 139 | compile 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | org.eclipse.jetty 149 | jetty-maven-plugin 150 | ${jetty.plugin.version} 151 | 152 | 2 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | vaadin-prerelease 164 | 165 | false 166 | 167 | 168 | 169 | 170 | vaadin-prereleases 171 | http://maven.vaadin.com/vaadin-prereleases 172 | 173 | 174 | 175 | 176 | vaadin-prereleases 177 | http://maven.vaadin.com/vaadin-prereleases 178 | 179 | 180 | 181 | 182 | 183 | 184 | -------------------------------------------------------------------------------- /vaadin-excel-exporter-demo/src/main/java/org/vaadin/addons/excelexporter/demo/DataModel.java: -------------------------------------------------------------------------------- 1 | package org.vaadin.addons.excelexporter.demo; 2 | 3 | /** 4 | * 5 | * @author Kartik Suba 6 | * 7 | */ 8 | public class DataModel { 9 | 10 | private String country = null; 11 | private String productType = null; 12 | private String catalogue = null; 13 | private String plannedPrinter = null; 14 | private String cheapest = null; 15 | private String contractor = null; 16 | private Double totalCosts = null; 17 | private Double differenceToMin = null; 18 | private String comment = null; 19 | private String coverPartner = null; 20 | private String contentProduction = null; 21 | private String contentPaper = null; 22 | private String contentFinishing = null; 23 | private String contentSender = null; 24 | private Double contentPrintCost = null; 25 | private Double contentPaperCost = null; 26 | private Double finishingCost = null; 27 | private Double finishingTruckCost = null; 28 | private Double senderCost = null; 29 | private Double frightCoverToFinishingCost = null; 30 | private Double diffToMinTransportContent = null; 31 | private Boolean active; 32 | 33 | public Boolean getActive() { 34 | return this.active; 35 | } 36 | 37 | public void setActive(final Boolean active) { 38 | this.active = active; 39 | } 40 | 41 | public Integer getCounter() { 42 | return this.counter; 43 | } 44 | 45 | public void setCounter(final Integer counter) { 46 | this.counter = counter; 47 | } 48 | 49 | Integer counter; 50 | 51 | public String getCountry() { 52 | return this.country; 53 | } 54 | 55 | public void setCountry(final String country) { 56 | this.country = country; 57 | } 58 | 59 | public String getProductType() { 60 | return this.productType; 61 | } 62 | 63 | public void setProductType(final String productType) { 64 | this.productType = productType; 65 | } 66 | 67 | public String getCatalogue() { 68 | return this.catalogue; 69 | } 70 | 71 | public void setCatalogue(final String catalogue) { 72 | this.catalogue = catalogue; 73 | } 74 | 75 | public String getPlannedPrinter() { 76 | return this.plannedPrinter; 77 | } 78 | 79 | public void setPlannedPrinter(final String plannedPrinter) { 80 | this.plannedPrinter = plannedPrinter; 81 | } 82 | 83 | public String getCheapest() { 84 | return this.cheapest; 85 | } 86 | 87 | public void setCheapest(final String cheapest) { 88 | this.cheapest = cheapest; 89 | } 90 | 91 | public String getContractor() { 92 | return this.contractor; 93 | } 94 | 95 | public void setContractor(final String contractor) { 96 | this.contractor = contractor; 97 | } 98 | 99 | public String getCoverPartner() { 100 | return this.coverPartner; 101 | } 102 | 103 | public void setCoverPartner(final String coverPartner) { 104 | this.coverPartner = coverPartner; 105 | } 106 | 107 | public String getContentProduction() { 108 | return this.contentProduction; 109 | } 110 | 111 | public void setContentProduction(final String contentProduction) { 112 | this.contentProduction = contentProduction; 113 | } 114 | 115 | public String getContentPaper() { 116 | return this.contentPaper; 117 | } 118 | 119 | public void setContentPaper(final String contentPaper) { 120 | this.contentPaper = contentPaper; 121 | } 122 | 123 | public String getContentFinishing() { 124 | return this.contentFinishing; 125 | } 126 | 127 | public void setContentFinishing(final String contentFinishing) { 128 | this.contentFinishing = contentFinishing; 129 | } 130 | 131 | public String getContentSender() { 132 | return this.contentSender; 133 | } 134 | 135 | public void setContentSender(final String contentSender) { 136 | this.contentSender = contentSender; 137 | } 138 | 139 | public Double getTotalCosts() { 140 | return this.totalCosts; 141 | } 142 | 143 | public void setTotalCosts(final Double totalCosts) { 144 | this.totalCosts = totalCosts; 145 | } 146 | 147 | public Double getDifferenceToMin() { 148 | return this.differenceToMin; 149 | } 150 | 151 | public void setDifferenceToMin(final Double differenceToMin) { 152 | this.differenceToMin = differenceToMin; 153 | } 154 | 155 | public String getComment() { 156 | return this.comment; 157 | } 158 | 159 | public void setComment(final String comment) { 160 | this.comment = comment; 161 | } 162 | 163 | public Double getContentPrintCost() { 164 | return this.contentPrintCost; 165 | } 166 | 167 | public void setContentPrintCost(final Double contentPrintCost) { 168 | this.contentPrintCost = contentPrintCost; 169 | } 170 | 171 | public Double getContentPaperCost() { 172 | return this.contentPaperCost; 173 | } 174 | 175 | public void setContentPaperCost(final Double contentPaperCost) { 176 | this.contentPaperCost = contentPaperCost; 177 | } 178 | 179 | public Double getFinishingCost() { 180 | return this.finishingCost; 181 | } 182 | 183 | public void setFinishingCost(final Double finishingCost) { 184 | this.finishingCost = finishingCost; 185 | } 186 | 187 | public Double getFinishingTruckCost() { 188 | return this.finishingTruckCost; 189 | } 190 | 191 | public void setFinishingTruckCost(final Double finishingTruckCost) { 192 | this.finishingTruckCost = finishingTruckCost; 193 | } 194 | 195 | public Double getSenderCost() { 196 | return this.senderCost; 197 | } 198 | 199 | public void setSenderCost(final Double senderCost) { 200 | this.senderCost = senderCost; 201 | } 202 | 203 | public Double getFrightCoverToFinishingCost() { 204 | return this.frightCoverToFinishingCost; 205 | } 206 | 207 | public void setFrightCoverToFinishingCost(final Double frightCoverToFinishingCost) { 208 | this.frightCoverToFinishingCost = frightCoverToFinishingCost; 209 | } 210 | 211 | public Double getDiffToMinTransportContent() { 212 | return this.diffToMinTransportContent; 213 | } 214 | 215 | public void setDiffToMinTransportContent(final Double diffToMinTransportContent) { 216 | this.diffToMinTransportContent = diffToMinTransportContent; 217 | } 218 | 219 | } 220 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | org.vaadin.addons 6 | vaadin-excel-exporter 7 | jar 8 | 2.1-SNAPSHOT 9 | Excel Exporter 10 | 11 | 12 | 3 13 | 14 | 15 | 16 | UTF-8 17 | 1.8 18 | 1.8 19 | 8.4.3 20 | 8.0.6 21 | 22 | 23 | ${project.version} 24 | 25 | ${project.name} 26 | ${project.organization.name} 27 | Apache License 2.0 28 | ${project.artifactId}-${project.version}.jar 29 | 1.7.12 30 | 31 | 32 | 33 | Kartik Suba (Direction Software Solutions) 34 | https://github.com/bonprix/vaadin-excel-exporter 35 | 36 | 37 | 38 | git://github.com/bonprix/vaadin-excel-exporter.git 39 | scm:git:git://github.com/bonprix/vaadin-excel-exporter.git 40 | scm:git:ssh://git@github.com:/bonprix/vaadin-excel-exporter.git 41 | 42 | 43 | 44 | GitHub 45 | https://github.com/bonprix/vaadin-excel-exporter/issues 46 | 47 | 48 | 49 | 50 | The MIT License (MIT) 51 | http://opensource.org/licenses/MIT 52 | 53 | 54 | 55 | 56 | 57 | vaadin-addons 58 | http://maven.vaadin.com/vaadin-addons 59 | 60 | 61 | 62 | 63 | 64 | com.vaadin 65 | vaadin-server 66 | ${vaadin.version} 67 | 68 | 69 | com.vaadin 70 | vaadin-client 71 | ${vaadin.version} 72 | provided 73 | 74 | 75 | 76 | 77 | junit 78 | junit 79 | 4.8.1 80 | test 81 | 82 | 83 | 84 | 85 | net.karneim 86 | pojobuilder 87 | 4.2.2 88 | 89 | 90 | 91 | 92 | org.apache.poi 93 | poi-ooxml 94 | 3.17 95 | 96 | 97 | 98 | org.slf4j 99 | slf4j-api 100 | ${slf4j.version} 101 | 102 | 103 | org.slf4j 104 | jul-to-slf4j 105 | ${slf4j.version} 106 | 107 | 108 | 109 | 110 | 111 | 112 | org.apache.maven.plugins 113 | maven-jar-plugin 114 | 2.6 115 | 116 | 117 | true 118 | 119 | true 120 | true 121 | 122 | 123 | 124 | 1 125 | ${Vaadin-License-Title} 126 | org.vaadin.addons.WidgetSet 127 | 128 | 129 | 130 | 131 | 132 | 133 | org.apache.maven.plugins 134 | maven-javadoc-plugin 135 | 2.10.3 136 | 137 | 138 | attach-javadoc 139 | 140 | jar 141 | 142 | 143 | 144 | 145 | 146 | 147 | org.apache.maven.plugins 148 | maven-source-plugin 149 | 3.0.0 150 | 151 | 152 | attach-sources 153 | 154 | jar 155 | 156 | 157 | 158 | 159 | 160 | 161 | org.apache.maven.plugins 162 | maven-assembly-plugin 163 | 164 | false 165 | 166 | assembly/assembly.xml 167 | 168 | 169 | 170 | 171 | 172 | single 173 | 174 | install 175 | 176 | 177 | 178 | 179 | 180 | 181 | org.apache.maven.plugins 182 | maven-surefire-plugin 183 | 2.19.1 184 | 185 | 186 | 187 | 189 | 190 | 191 | src/main/java 192 | 193 | rebel.xml 194 | 195 | 196 | 197 | src/main/resources 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | vaadin-prerelease 207 | 208 | false 209 | 210 | 211 | 212 | 213 | vaadin-prereleases 214 | http://maven.vaadin.com/vaadin-prereleases 215 | 216 | 217 | vaadin-snapshots 218 | https://oss.sonatype.org/content/repositories/vaadin-snapshots/ 219 | 220 | false 221 | 222 | 223 | true 224 | 225 | 226 | 227 | 228 | 229 | vaadin-prereleases 230 | http://maven.vaadin.com/vaadin-prereleases 231 | 232 | 233 | vaadin-snapshots 234 | https://oss.sonatype.org/content/repositories/vaadin-snapshots/ 235 | 236 | false 237 | 238 | 239 | true 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/configuration/ExportExcelComponentConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.configuration; 5 | 6 | import java.awt.Color; 7 | import java.util.ArrayList; 8 | import java.util.LinkedHashMap; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.function.BiFunction; 12 | import net.karneim.pojobuilder.GeneratePojoBuilder; 13 | 14 | import org.apache.poi.ss.usermodel.CellStyle; 15 | import org.apache.poi.ss.usermodel.Font; 16 | import org.apache.poi.ss.usermodel.IndexedColors; 17 | import org.apache.poi.xssf.usermodel.XSSFCellStyle; 18 | import org.apache.poi.xssf.usermodel.XSSFColor; 19 | import org.apache.poi.xssf.usermodel.XSSFFont; 20 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 21 | import org.vaadin.addons.excelexporter.formatter.ColumnFormatter; 22 | import org.vaadin.addons.excelexporter.function.DataCellStyleGeneratorFunction; 23 | import org.vaadin.addons.excelexporter.utils.ExcelStyleUtil; 24 | 25 | import com.vaadin.ui.Grid; 26 | import org.apache.poi.ss.usermodel.FillPatternType; 27 | import org.apache.poi.ss.usermodel.HorizontalAlignment; 28 | 29 | /** 30 | * The Class ExportExcelComponentConfiguration is used to configure the 31 | * component as in Table, Tree Table or Grid Several additional properties such 32 | * as formatting, headers, footers, styles etc. can also be configured 33 | * 34 | * @author Kartik Suba 35 | */ 36 | @GeneratePojoBuilder(intoPackage = "*.builder") 37 | public class ExportExcelComponentConfiguration { 38 | 39 | /** The visible properties. */ 40 | private String[] visibleProperties; 41 | 42 | /** The date formatting properties. */ 43 | private List dateFormattingProperties; 44 | 45 | /** The integer formatting properties. */ 46 | private List integerFormattingProperties; 47 | 48 | /** The float formatting properties. */ 49 | private List floatFormattingProperties; 50 | 51 | /** The boolean formatting properties. */ 52 | private List booleanFormattingProperties; 53 | 54 | /** The header configs. */ 55 | private List headerConfigs; 56 | 57 | /** The footer configs. */ 58 | private List footerConfigs; 59 | 60 | /** The table header style function. */ 61 | private BiFunction headerStyleFunction = (workbook, columnId) -> { 62 | XSSFCellStyle headerCellStyle = workbook.createCellStyle(); 63 | headerCellStyle.setFillForegroundColor(new XSSFColor(new Color(50, 86, 110))); 64 | headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); 65 | headerCellStyle.setAlignment(HorizontalAlignment.LEFT); 66 | headerCellStyle = ExcelStyleUtil.setBorders(headerCellStyle, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, 67 | Boolean.TRUE, Color.WHITE); 68 | 69 | XSSFFont boldFont = workbook.createFont(); 70 | boldFont.setColor(IndexedColors.WHITE.getIndex()); 71 | boldFont.setBold(true); 72 | 73 | headerCellStyle.setFont(boldFont); 74 | 75 | return headerCellStyle; 76 | }; 77 | 78 | /** The table footer style function. */ 79 | private BiFunction footerStyleFunction = (workbook, columnId) -> { 80 | XSSFCellStyle headerCellStyle = workbook.createCellStyle(); 81 | headerCellStyle.setFillForegroundColor(new XSSFColor(new Color(50, 86, 110))); 82 | headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); 83 | headerCellStyle.setAlignment(HorizontalAlignment.LEFT); 84 | headerCellStyle = ExcelStyleUtil.setBorders(headerCellStyle, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, 85 | Boolean.TRUE, Color.WHITE); 86 | 87 | XSSFFont boldFont = workbook.createFont(); 88 | boldFont.setColor(IndexedColors.WHITE.getIndex()); 89 | boldFont.setBold(true); 90 | 91 | headerCellStyle.setFont(boldFont); 92 | 93 | return headerCellStyle; 94 | }; 95 | 96 | /** The table content style function. */ 97 | private DataCellStyleGeneratorFunction contentStyleFunction = (workbook, columnId, value, rowNum) -> { 98 | XSSFCellStyle cellStyle = workbook.createCellStyle(); 99 | 100 | if (rowNum % 2 == 1) { 101 | cellStyle.setFillForegroundColor(new XSSFColor(new Color(228, 234, 238))); 102 | cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); 103 | } 104 | 105 | return cellStyle; 106 | }; 107 | 108 | /** The column formatters. */ 109 | private Map columnFormatters = new LinkedHashMap<>(); 110 | 111 | /** The grid. */ 112 | private Grid grid; 113 | 114 | /** 115 | * Gets the grid. 116 | * 117 | * @return the grid 118 | */ 119 | public Grid getGrid() { 120 | return this.grid; 121 | } 122 | 123 | /** 124 | * Sets the grid. 125 | * 126 | * @param grid 127 | * the new grid 128 | */ 129 | public void setGrid(final Grid grid) { 130 | this.grid = grid; 131 | } 132 | 133 | public BiFunction getHeaderStyleFunction() { 134 | return this.headerStyleFunction; 135 | } 136 | 137 | public void setHeaderStyleFunction(BiFunction headerStyleFunction) { 138 | this.headerStyleFunction = headerStyleFunction; 139 | } 140 | 141 | public BiFunction getFooterStyleFunction() { 142 | return this.footerStyleFunction; 143 | } 144 | 145 | public void setFooterStyleFunction(BiFunction footerStyleFunction) { 146 | this.footerStyleFunction = footerStyleFunction; 147 | } 148 | 149 | public DataCellStyleGeneratorFunction getContentStyleFunction() { 150 | return this.contentStyleFunction; 151 | } 152 | 153 | public void setContentStyleFunction(DataCellStyleGeneratorFunction contentStyleFunction) { 154 | this.contentStyleFunction = contentStyleFunction; 155 | } 156 | 157 | /** 158 | * Gets the date formatting properties. 159 | * 160 | * @return the date formatting properties 161 | */ 162 | public List getDateFormattingProperties() { 163 | if (this.dateFormattingProperties == null) { 164 | this.dateFormattingProperties = new ArrayList<>(); 165 | } 166 | return this.dateFormattingProperties; 167 | } 168 | 169 | /** 170 | * Sets the date formatting properties. 171 | * 172 | * @param dateFormattingProperties 173 | * the new date formatting properties 174 | */ 175 | public void setDateFormattingProperties(final List dateFormattingProperties) { 176 | this.dateFormattingProperties = dateFormattingProperties; 177 | } 178 | 179 | /** 180 | * Gets the integer formatting properties. 181 | * 182 | * @return the integer formatting properties 183 | */ 184 | public List getIntegerFormattingProperties() { 185 | if (this.integerFormattingProperties == null) { 186 | this.integerFormattingProperties = new ArrayList<>(); 187 | } 188 | return this.integerFormattingProperties; 189 | } 190 | 191 | /** 192 | * Sets the integer formatting properties. 193 | * 194 | * @param integerFormattingProperties 195 | * the new integer formatting properties 196 | */ 197 | public void setIntegerFormattingProperties(final List integerFormattingProperties) { 198 | this.integerFormattingProperties = integerFormattingProperties; 199 | } 200 | 201 | /** 202 | * Gets the float formatting properties. 203 | * 204 | * @return the float formatting properties 205 | */ 206 | public List getFloatFormattingProperties() { 207 | if (this.floatFormattingProperties == null) { 208 | this.floatFormattingProperties = new ArrayList<>(); 209 | } 210 | return this.floatFormattingProperties; 211 | } 212 | 213 | /** 214 | * Sets the float formatting properties. 215 | * 216 | * @param floatFormattingProperties 217 | * the new float formatting properties 218 | */ 219 | public void setFloatFormattingProperties(final List floatFormattingProperties) { 220 | this.floatFormattingProperties = floatFormattingProperties; 221 | } 222 | 223 | /** 224 | * Sets the boolean formatting properties. 225 | * 226 | * @param booleanFormattingProperties 227 | * the new boolean formatting properties 228 | */ 229 | public void setBooleanFormattingProperties(final List booleanFormattingProperties) { 230 | this.booleanFormattingProperties = booleanFormattingProperties; 231 | } 232 | 233 | /** 234 | * Sets the header configs. 235 | * 236 | * @param headerConfigs 237 | * the new header configs 238 | */ 239 | public void setHeaderConfigs(final List headerConfigs) { 240 | this.headerConfigs = headerConfigs; 241 | } 242 | 243 | /** 244 | * Sets the footer configs. 245 | * 246 | * @param footerConfigs 247 | * the new footer configs 248 | */ 249 | public void setFooterConfigs(final List footerConfigs) { 250 | this.footerConfigs = footerConfigs; 251 | } 252 | 253 | /** 254 | * Sets the column formatters. 255 | * 256 | * @param columnFormatters 257 | * the column formatters 258 | */ 259 | public void setColumnFormatters(final Map columnFormatters) { 260 | this.columnFormatters = columnFormatters; 261 | } 262 | 263 | /** 264 | * Gets the visible properties. 265 | * 266 | * @return the visible properties 267 | */ 268 | public String[] getVisibleProperties() { 269 | return this.visibleProperties; 270 | } 271 | 272 | /** 273 | * Sets the visible properties. 274 | * 275 | * @param visibleProperties 276 | * the new visible properties 277 | */ 278 | public void setVisibleProperties(final String[] visibleProperties) { 279 | this.visibleProperties = visibleProperties; 280 | } 281 | 282 | /** 283 | * Gets the boolean formatting properties. 284 | * 285 | * @return the boolean formatting properties 286 | */ 287 | public List getBooleanFormattingProperties() { 288 | if (this.booleanFormattingProperties == null) { 289 | this.booleanFormattingProperties = new ArrayList<>(); 290 | } 291 | return this.booleanFormattingProperties; 292 | } 293 | 294 | /** 295 | * Gets the header configs. 296 | * 297 | * @return the header configs 298 | */ 299 | public List getHeaderConfigs() { 300 | return this.headerConfigs; 301 | } 302 | 303 | /** 304 | * Gets the footer configs. 305 | * 306 | * @return the footer configs 307 | */ 308 | public List getFooterConfigs() { 309 | return this.footerConfigs; 310 | } 311 | 312 | /** 313 | * Gets the column formatters. 314 | * 315 | * @return the column formatters 316 | */ 317 | public Map getColumnFormatters() { 318 | return this.columnFormatters; 319 | } 320 | 321 | /** 322 | * Gets the column formatter. 323 | * 324 | * @param columnId 325 | * the column id 326 | * @return the column formatter 327 | */ 328 | public ColumnFormatter getColumnFormatter(final Object columnId) { 329 | if (this.columnFormatters != null && !this.columnFormatters.isEmpty() 330 | && this.columnFormatters.containsKey(columnId)) { 331 | return this.columnFormatters.get(columnId); 332 | } 333 | return null; 334 | } 335 | } 336 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vaadin-excel-exporter for Vaadin 8 2 | 3 | vaadin-excel-exporter is a utility add-on for Vaadin 8. 4 | It is a single point solution providing consistent 5 | and configurable support for 6 | exporting data of Vaadin in Excel format. 7 | 8 | Grid only works with ListDataProvider, open for pullrequest ideas for other Providers. 9 | 10 | ## Why do we need this addon? 11 | 12 | 1) Exporting the screen data is a frequent task required in most of the applications. There are several 13 | helper technologies such as POI which help us in bringing the Export feature in place but a developer 14 | needs to take it up every time he wants to implement. 15 | 2) Vaadin providing so many components for representation of data such as Table, Tree Table and Grid, 16 | which again raises a need for a utility that is easy and configurable to be used with varied component 17 | wihtout the pain of writing the logic to generate the Excel. 18 | 3) A consistent excel format throughout the application which would enhance user experience. 19 | 4) Can be integrated with any Vaadin application with just few lines of configuration code. 20 | 21 | ## What dependencies are required? 22 | JDK 1.8 or above 23 | POI 3.9 24 | POI-OOXML 3.9 25 | Apache Commons IO library (http://commons.apache.org/io/) v2.2 26 | 27 | ## Features 28 | 29 | It is highly configurable and provides configuration at three levels namely File Level, Sheet Level, Component Level. 30 | 31 | ### For each file you can configure 32 | - List of Sheets 33 | - Export File Name 34 | - Generated By 35 | - Export Type (xlsx or xls) 36 | 37 | ### For each sheet you can configure 38 | - Sheet Name 39 | - Report Title Row 40 | - Generated By Row 41 | - Frozen Columns 42 | - Frozen Rows 43 | - List of Components inside the sheet 44 | - FieldGroup - for showing filters selected on the screen for the selected data 45 | - Additional Header Info - HashMap for custom data (Key Value Pair) 46 | - Date Format 47 | - Number Formats 48 | - XSSFCellStyle for each content section of the screen 49 | 50 | Note that the Number formats by itself manages the thousand separator and decimal point 51 | for different locales. For Eg: For English the decimal point is (.) and thousand separator is (,), but for 52 | German locale it is the reverse. But the code handles it by its own. 53 | 54 | ### For each component you can configure 55 | - Component - Grid 56 | - It only supports one dataprovider for now - ListDataProvider 57 | - Visible properties 58 | - Properties requiring date formatting 59 | - Properties requiring Float formatting 60 | - Properties requiring Integer formatting 61 | - Column Header Texts 62 | - Column Header Auto Filter (only one auto filter per sheet) 63 | - Component Header, Footer and Content Styles 64 | -- very specific can do different styling on rowNum, columnId, value 65 | - Provide Column Formatters. Use built in Suffix, Prefix formatters. 66 | - Multiple Header Rows (and merging columns) 67 | - Multiple Footer Rows (and merging columns) 68 | - Info: Still dont like the merging of columns api, doesn't support drag&drop of columns 69 | -- but seems like not that big of an issue yet, otherwise please create a issue :) 70 | 71 | However, if none of these are specified, it would generate the Excel with default values and styles. 72 | 73 | ## Online demo 74 | coming soon... 75 | For demo just check it out and start your local jetty, please look down for instructions 76 | 77 | ## Usage 78 | 79 | ### Maven 80 | 81 | ```xml 82 | 83 | org.vaadin.addons 84 | vaadin-excel-exporter 85 | 2.0 86 | 87 | 88 | 89 | vaadin-addons 90 | http://maven.vaadin.com/vaadin-addons 91 | 92 | ``` 93 | 94 | No widgetset required. 95 | 96 | ## Download release 97 | 98 | Official releases of this add-on are available at Vaadin Directory. For Maven instructions, download and reviews, go to http://vaadin.com/addon/vaadin-excel-exporter 99 | 100 | ## Building and running demo 101 | 102 | git clone https://github.com/bonprix/vaadin-excel-exporter 103 | mvn clean install 104 | cd demo 105 | mvn jetty:run 106 | 107 | To see the demo, navigate to http://localhost:8080/ 108 | 109 | ## Development with Eclipse IDE 110 | 111 | For further development of this add-on, the following tool-chain is recommended: 112 | - Eclipse IDE 113 | - m2e wtp plug-in (install it from Eclipse Marketplace) 114 | - Vaadin Eclipse plug-in (install it from Eclipse Marketplace) 115 | - JRebel Eclipse plug-in (install it from Eclipse Marketplace) 116 | - Chrome browser 117 | 118 | ### Importing project 119 | 120 | Choose File > Import... > Existing Maven Projects 121 | 122 | Note that Eclipse may give "Plugin execution not covered by lifecycle configuration" errors for pom.xml. Use "Permanently mark goal resources in pom.xml as ignored in Eclipse build" quick-fix to mark these errors as permanently ignored in your project. Do not worry, the project still works fine. 123 | 124 | # Developer Guide 125 | 126 | ## Getting started 127 | 128 | Here is a simple example on how to try out the add-on component: 129 | 130 | ```java 131 | /* Configuring Components */ 132 | ExportExcelComponentConfiguration componentConfig1 133 | = new ExportExcelComponentConfigurationBuilder() 134 | .withGrid(this.gridDefault) 135 | .withVisibleProperties(this.visibleColumns) 136 | .withHeaderConfigs(Arrays.asList( 137 | new ComponentHeaderConfigurationBuilder() 138 | .withAutoFilter(true) 139 | .withColumnKeys(this.columnHeaders) 140 | .build() 141 | ) 142 | ) 143 | .withIntegerFormattingProperties(Arrays.asList("counter")) 144 | .withFloatFormattingProperties(Arrays.asList( 145 | "totalCosts", 146 | "differenceToMin") 147 | ) 148 | .withBooleanFormattingProperties(Arrays.asList("active")) 149 | .withColumnFormatters(columnFormatters) 150 | .build(); 151 | 152 | /* Configuring Sheets */ 153 | ExportExcelSheetConfiguration sheetConfig1 154 | = new ExportExcelSheetConfigurationBuilder() 155 | .withReportTitle("Grid (Default)") 156 | .withSheetName("Grid (default)") 157 | .withComponentConfigs(Arrays.asList(componentConfig1)) 158 | .withIsHeaderSectionRequired(Boolean.TRUE) 159 | .withDateFormat("dd-MMM-yyyy") 160 | .build(); 161 | 162 | /* Configuring Excel */ 163 | ExportExcelConfiguration config1 164 | = new ExportExcelConfigurationBuilder() 165 | .withGeneratedBy("Kartik Suba") 166 | .withSheetConfigs(Arrays.asList(sheetConfig1)) 167 | .build(); 168 | 169 | /* execute the export */ 170 | config1.export(); 171 | ``` 172 | 173 | For a more comprehensive example, see src/test/java/org/vaadin/template/demo/DemoUI.java 174 | 175 | ### Debugging server-side 176 | 177 | If you have not already compiled the widgetset, do it now by running vaadin:install Maven target for vaadin-excel-exporter-root project. 178 | 179 | If you have a JRebel license, it makes on the fly code changes faster. Just add JRebel nature to your vaadin-excel-exporter-demo project by clicking project with right mouse button and choosing JRebel > Add JRebel Nature 180 | 181 | To debug project and make code modifications on the fly in the server-side, right-click the vaadin-excel-exporter-demo project and choose Debug As > Debug on Server. Navigate to http://localhost:8080/vaadin-excel-exporter-demo/ to see the application. 182 | 183 | ### Debugging client-side 184 | 185 | Debugging client side code in the vaadin-excel-exporter-demo project: 186 | - run "mvn vaadin:run-codeserver" on a separate console while the application is running 187 | - activate Super Dev Mode in the debug window of the application or by adding ?superdevmode to the URL 188 | - You can access Java-sources and set breakpoints inside Chrome if you enable source maps from inspector settings. 189 | 190 | ## Release notes 191 | 192 | ### Version 2.0 193 | 194 | - migrated it to Vaadin 8 195 | -- removed all kind of tables 196 | - improved some functionality like auto filter, cell style generators are now more specific and more 197 | - refactored all of the code 198 | -- removed all reflection 199 | 200 | ### Version 1.0.5 201 | 202 | - Added support for nested properties in case of BeanItemContainer. 203 | 204 | - Resolved issues raised in git 205 | - https://github.com/bonprix/vaadin-excel-exporter/issues/3 206 | - https://github.com/bonprix/vaadin-excel-exporter/issues/9 207 | - https://github.com/bonprix/vaadin-excel-exporter/pull/16 208 | 209 | - Updated the Demo Project to show case the same. 210 | 211 | ### Version 1.0.4 212 | - Added ComponentHeaderConfiguration and ComponentFooterConfiguration 213 | 214 | - These would allow the user to configure multiple headers and footers for each component. 215 | 216 | - The ComponentHeaderConfiguration provides support for Grid.HeaderRow so in case you have appended headers in your grid, you can pass them directly to the header configuration. 217 | - However, it also supports custom header through String[] 218 | - You can also merge the header cells by specifying the start property, end property and display string in the MergedCell bean. 219 | 220 | - Similar support is available for ComponentFooterConfiguration 221 | 222 | - Updated the Demo Project to showcase the same. Also you can refer to the advance snipped section for example. 223 | 224 | ### Version 1.0.3 225 | - Added Column Formatter Logic 226 | 227 | - Also developed three formatters as built in formatters namely 228 | - SuffixColumnFormatter(String suffix) // can add suffix to the container/model value such as $, %, kg etc... 229 | - PrefixColumnFormatter(String prefix // can add prefix to the container/model value 230 | - BooleanColumnFormatter(String trueValue, String falseValue) // Give meaningful alias to true and false like Yes/No, Active/De-Active etc.. Requires the column to be also set withBooleanFormattingProperties 231 | 232 | - Note: For columns mentioned in withFloatFormattingProperties and withIntegerFormattingProperties, the above formatting gets applied after the Integer and Float formatting is performed on the container/model value. 233 | 234 | ### Version 1.0.2 235 | - Added Getters for extension 236 | 237 | ### Version 1.0.1 238 | - Initial release 239 | 240 | ## Roadmap 241 | 242 | Recently Released : 243 | - Reflecting some column generator logic as well in the Excel. For Example suffixes cm, kg, $ etc... 244 | 245 | Upcoming releases: 246 | - Specifying Excel Column types as Date, Number sustaining their formatting 247 | - Specifying a row header which can allow horizontal data as well. 248 | - Export of selected records wherever applicable 249 | - Legend for better understanding 250 | 251 | ## Issue tracking 252 | 253 | The issues for this add-on are tracked on its github.com page. All bug reports and feature requests are appreciated. 254 | 255 | ## Contributions 256 | 257 | Contributions are welcome, but there are no guarantees that they are accepted as such. Process for contributing is the following: 258 | - Fork this project 259 | - Create an issue to this project about the contribution (bug or feature) if there is no such issue about it already. Try to keep the scope minimal. 260 | - Develop and test the fix or functionality carefully. Only include minimum amount of code needed to fix the issue. 261 | - Refer to the fixed issue in commit 262 | - Send a pull request for the original project 263 | - Comment on the original issue that you have implemented a fix for it 264 | 265 | ## License & Author 266 | 267 | Add-on is distributed under Apache License 2.0. For license terms, see LICENSE.txt. 268 | 269 | vaadin-excel-exporter is written by Kartik Suba @ Direction Software Solutions, India. 270 | For Client: Bonprix Handelsgesellschaft mbH -------------------------------------------------------------------------------- /vaadin-excel-exporter-demo/src/main/java/org/vaadin/addons/excelexporter/demo/DemoUI.java: -------------------------------------------------------------------------------- 1 | package org.vaadin.addons.excelexporter.demo; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | 6 | import javax.servlet.annotation.WebServlet; 7 | 8 | import org.vaadin.addons.excelexporter.ExportToExcel; 9 | import org.vaadin.addons.excelexporter.configuration.ExportExcelComponentConfiguration; 10 | import org.vaadin.addons.excelexporter.configuration.ExportExcelConfiguration; 11 | import org.vaadin.addons.excelexporter.configuration.ExportExcelSheetConfiguration; 12 | import org.vaadin.addons.excelexporter.configuration.builder.ComponentFooterConfigurationBuilder; 13 | import org.vaadin.addons.excelexporter.configuration.builder.ComponentHeaderConfigurationBuilder; 14 | import org.vaadin.addons.excelexporter.configuration.builder.ExportExcelComponentConfigurationBuilder; 15 | import org.vaadin.addons.excelexporter.configuration.builder.ExportExcelConfigurationBuilder; 16 | import org.vaadin.addons.excelexporter.configuration.builder.ExportExcelSheetConfigurationBuilder; 17 | import org.vaadin.addons.excelexporter.configuration.builder.MergedCellBuilder; 18 | import org.vaadin.addons.excelexporter.demo.data.DataModelGenerator; 19 | import org.vaadin.addons.excelexporter.formatter.BooleanColumnFormatter; 20 | import org.vaadin.addons.excelexporter.formatter.ColumnFormatter; 21 | import org.vaadin.addons.excelexporter.formatter.SuffixColumnFormatter; 22 | import org.vaadin.addons.excelexporter.model.ExportType; 23 | 24 | import com.vaadin.annotations.Title; 25 | import com.vaadin.annotations.VaadinServletConfiguration; 26 | import com.vaadin.annotations.Widgetset; 27 | import com.vaadin.data.provider.ListDataProvider; 28 | import com.vaadin.icons.VaadinIcons; 29 | import com.vaadin.server.VaadinRequest; 30 | import com.vaadin.server.VaadinServlet; 31 | import com.vaadin.ui.Grid; 32 | import com.vaadin.ui.MenuBar; 33 | import com.vaadin.ui.TabSheet; 34 | import com.vaadin.ui.UI; 35 | import com.vaadin.ui.VerticalLayout; 36 | import com.vaadin.ui.components.grid.FooterCell; 37 | import com.vaadin.ui.components.grid.FooterRow; 38 | import com.vaadin.ui.components.grid.HeaderCell; 39 | import com.vaadin.ui.components.grid.HeaderRow; 40 | 41 | /** 42 | * 43 | * @author Kartik Suba 44 | * 45 | */ 46 | @Title("vaadin-excel-exporter Add-on Demo") 47 | @SuppressWarnings("serial") 48 | @Widgetset("AppWidgetset") 49 | public class DemoUI extends UI { 50 | 51 | private Grid gridDefault; 52 | private Grid gridMergedCells; 53 | private Grid gridFrozenColumns; 54 | 55 | private transient String[] visibleColumns = new String[] { "country", "productType", "catalogue", "plannedPrinter", 56 | "cheapest", "contractor", "totalCosts", "differenceToMin", "comment", "active", "counter" }; 57 | private transient String[] columnHeaders = new String[] { "COUNTRY", "PRODUCT_TYPE", "CATALOGUE", "PLANNED_PRINTER", 58 | "CHEAPEST", "CONTRACTOR", "TOTAL_COST", "DIFFERENCE_TO_MIN", "COMMENT", "ACTIVE", "COUNTER" }; 59 | 60 | @WebServlet(value = "/*", asyncSupported = true) 61 | @VaadinServletConfiguration(productionMode = false, ui = DemoUI.class, widgetset = "org.vaadin.addons.demo.DemoWidgetSet") 62 | public static class Servlet extends VaadinServlet { 63 | } 64 | 65 | @Override 66 | protected void init(final VaadinRequest request) { 67 | 68 | // Creating the Export Tool Bar 69 | MenuBar exportToolBar = createToolBar(); 70 | 71 | final VerticalLayout layout = new VerticalLayout(); 72 | layout.setSizeFull(); 73 | 74 | // Adding the Export Tool Bar to the Layout 75 | layout.addComponent(exportToolBar); 76 | 77 | /********* 78 | * Adding Components to the Layout namely Tables, Grids and Tree Table 79 | *******/ 80 | this.gridDefault = new Grid<>(DataModel.class); 81 | this.gridDefault.setDataProvider(new ListDataProvider<>(DataModelGenerator.generate(20))); 82 | this.gridDefault.setSizeFull(); 83 | this.gridDefault.setColumns(this.visibleColumns); 84 | 85 | this.gridMergedCells = new Grid<>(DataModel.class); 86 | this.gridMergedCells.setDataProvider(new ListDataProvider<>(DataModelGenerator.generate(20))); 87 | this.gridMergedCells.setColumns(this.visibleColumns); 88 | this.gridMergedCells.setSizeFull(); 89 | HeaderRow headerRow = this.gridMergedCells.addHeaderRowAt(0); 90 | HeaderCell joinHeaderColumns1 = headerRow.join("country", "productType"); 91 | joinHeaderColumns1.setText("mergedCell"); 92 | HeaderCell joinHeaderColumns2 = headerRow.join("cheapest", "contractor"); 93 | joinHeaderColumns2.setText("mergedCell"); 94 | FooterRow footerRow1 = this.gridMergedCells.addFooterRowAt(0); 95 | FooterCell joinFooterColumns1 = footerRow1.join("country", "productType"); 96 | joinFooterColumns1.setText("mergedCell"); 97 | FooterCell joinFooterColumns2 = footerRow1.join("cheapest", "contractor"); 98 | joinFooterColumns2.setText("mergedCell"); 99 | FooterRow footerRow2 = this.gridMergedCells.addFooterRowAt(0); 100 | for (int i = 0; i < this.visibleColumns.length; i++) { 101 | footerRow2.getCell(this.visibleColumns[i]) 102 | .setText(this.columnHeaders[i]); 103 | } 104 | 105 | this.gridFrozenColumns = new Grid<>(DataModel.class); 106 | this.gridFrozenColumns.setDataProvider(new ListDataProvider<>(DataModelGenerator.generate(20))); 107 | this.gridFrozenColumns.setColumns(this.visibleColumns); 108 | this.gridFrozenColumns.getColumn("country") 109 | .setWidth(300); 110 | this.gridFrozenColumns.getColumn("productType") 111 | .setWidth(300); 112 | this.gridFrozenColumns.getColumn("catalogue") 113 | .setWidth(300); 114 | this.gridFrozenColumns.setSizeFull(); 115 | this.gridFrozenColumns.setFrozenColumnCount(3); 116 | 117 | TabSheet tabSheet = new TabSheet(); 118 | tabSheet.setSizeFull(); 119 | tabSheet.addTab(this.gridDefault, "Grid (Default)"); 120 | tabSheet.addTab(this.gridMergedCells, "Grid (Merged Cells)"); 121 | tabSheet.addTab(this.gridFrozenColumns, "Grid (Frozen Columns&Rows)"); 122 | layout.addComponent(tabSheet); 123 | layout.setExpandRatio(tabSheet, 1); 124 | 125 | /********* 126 | * Adding Components to the Layout namely Tables, Grids and Tree Table 127 | *******/ 128 | 129 | /********* 130 | * Adding the above data to the containers or components 131 | *******/ 132 | 133 | setContent(layout); 134 | } 135 | 136 | /** 137 | * This method creates the tool bar with options XLSX and XLS. 138 | * 139 | * @return 140 | */ 141 | private MenuBar createToolBar() { 142 | MenuBar exportToolBar = new MenuBar(); 143 | 144 | exportToolBar.addItem("XLSX", VaadinIcons.DOWNLOAD, selectedItem -> { 145 | ExportToExcel exportToExcelUtility = customizeExportExcelUtility(ExportType.XLSX); 146 | exportToExcelUtility.export(); 147 | }); 148 | 149 | exportToolBar.addItem("XLS", VaadinIcons.DOWNLOAD, selectedItem -> { 150 | ExportToExcel exportToExcelUtility = customizeExportExcelUtility(ExportType.XLS); 151 | exportToExcelUtility.export(); 152 | }); 153 | 154 | return exportToolBar; 155 | } 156 | 157 | /** 158 | * Configuring ExportToExcel Utility This configuration allows the end 159 | * user-developer to \ Add multiple sheets and configure them separately \ 160 | * Configure components to be added in each sheet and their properties 161 | * 162 | * @param exportType 163 | * 164 | * @return ExportToExcelUtility 165 | */ 166 | private ExportToExcel customizeExportExcelUtility(ExportType exportType) { 167 | 168 | HashMap columnFormatters = new HashMap<>(); 169 | 170 | // Suffix Formatter provided 171 | columnFormatters.put("totalCosts", new SuffixColumnFormatter("$")); 172 | columnFormatters.put("differenceToMin", new SuffixColumnFormatter("$")); 173 | columnFormatters.put("cheapest", new SuffixColumnFormatter("-quite cheap")); 174 | 175 | // Boolean Formatter provided 176 | columnFormatters.put("active", new BooleanColumnFormatter("Yes", "No")); 177 | 178 | // Custom Formatting also possible 179 | columnFormatters.put("catalogue", (final Object value, final Object itemId, 180 | final Object columnId) -> (value != null) ? ((String) value).toLowerCase() : null); 181 | 182 | ExportExcelComponentConfiguration componentConfig1 = new ExportExcelComponentConfigurationBuilder() 183 | .withGrid(this.gridDefault) 184 | .withVisibleProperties(this.visibleColumns) 185 | .withHeaderConfigs(Arrays.asList(new ComponentHeaderConfigurationBuilder().withAutoFilter(true) 186 | .withColumnKeys(this.columnHeaders) 187 | .build())) 188 | .withIntegerFormattingProperties(Arrays.asList("counter")) 189 | .withFloatFormattingProperties(Arrays.asList("totalCosts", "differenceToMin")) 190 | .withBooleanFormattingProperties(Arrays.asList("active")) 191 | .withColumnFormatters(columnFormatters) 192 | .build(); 193 | 194 | ExportExcelComponentConfiguration componentConfig2 = new ExportExcelComponentConfigurationBuilder() 195 | .withGrid(this.gridMergedCells) 196 | .withVisibleProperties(this.visibleColumns) 197 | .withHeaderConfigs(Arrays.asList(new ComponentHeaderConfigurationBuilder() 198 | .withMergedCells(Arrays.asList(new MergedCellBuilder().withStartProperty("country") 199 | .withEndProperty("productType") 200 | .withHeaderKey("mergedCell") 201 | .build(), new MergedCellBuilder().withStartProperty("cheapest") 202 | .withEndProperty("contractor") 203 | .withHeaderKey("mergedCell") 204 | .build())) 205 | .withColumnKeys(this.columnHeaders) 206 | .build(), new ComponentHeaderConfigurationBuilder().withAutoFilter(true) 207 | .withColumnKeys(this.columnHeaders) 208 | .build())) 209 | .withFooterConfigs(Arrays 210 | .asList(new ComponentFooterConfigurationBuilder().withColumnKeys(this.columnHeaders) 211 | .build(), 212 | new ComponentFooterConfigurationBuilder() 213 | .withMergedCells(Arrays.asList(new MergedCellBuilder().withStartProperty("country") 214 | .withEndProperty("productType") 215 | .withHeaderKey("mergedCell") 216 | .build(), new MergedCellBuilder().withStartProperty("cheapest") 217 | .withEndProperty("contractor") 218 | .withHeaderKey("mergedCell") 219 | .build())) 220 | .withColumnKeys(this.columnHeaders) 221 | .build())) 222 | .withIntegerFormattingProperties(Arrays.asList("counter")) 223 | .withFloatFormattingProperties(Arrays.asList("totalCosts", "differenceToMin")) 224 | .withBooleanFormattingProperties(Arrays.asList("active")) 225 | .withColumnFormatters(columnFormatters) 226 | .build(); 227 | 228 | /* Configuring Sheets */ 229 | ExportExcelSheetConfiguration sheetConfig1 = new ExportExcelSheetConfigurationBuilder() 230 | .withReportTitle("Grid (Default)") 231 | .withSheetName("Grid (default)") 232 | .withComponentConfigs(Arrays.asList(componentConfig1)) 233 | .withIsHeaderSectionRequired(Boolean.TRUE) 234 | .withDateFormat("dd-MMM-yyyy") 235 | .build(); 236 | 237 | ExportExcelSheetConfiguration sheetConfig2 = new ExportExcelSheetConfigurationBuilder() 238 | .withReportTitle("Grid (Merged Cells)") 239 | .withSheetName("Grid (merged Cells)") 240 | .withComponentConfigs(Arrays.asList(componentConfig1)) 241 | .withIsHeaderSectionRequired(Boolean.TRUE) 242 | .withDateFormat("dd-MMM-yyyy") 243 | .build(); 244 | 245 | ExportExcelSheetConfiguration sheetConfig3 = new ExportExcelSheetConfigurationBuilder() 246 | .withReportTitle("Grid (Frozen Columns&Rows)") 247 | .withSheetName("Grid (Frozen Columns&Rows)") 248 | .withFrozenColumns(3) 249 | .withFrozenRows(5) 250 | .withComponentConfigs(Arrays.asList(componentConfig1)) 251 | .withIsHeaderSectionRequired(Boolean.TRUE) 252 | .withDateFormat("dd-MMM-yyyy") 253 | .build(); 254 | 255 | ExportExcelSheetConfiguration sheetConfig4 = new ExportExcelSheetConfigurationBuilder() 256 | .withReportTitle("Exported multiple Grids into one sheet") 257 | .withSheetName("Multiple Grids") 258 | .withComponentConfigs(Arrays.asList(componentConfig1, componentConfig2)) 259 | .withIsDefaultSheetTitleRequired(Boolean.FALSE) 260 | .withIsHeaderSectionRequired(Boolean.FALSE) 261 | .withDateFormat("dd-MMM-yyyy") 262 | .build(); 263 | 264 | /* Configuring Excel */ 265 | ExportExcelConfiguration config1 = new ExportExcelConfigurationBuilder() 266 | .withGeneratedBy("Kartik Suba") 267 | .withSheetConfigs(Arrays.asList(sheetConfig1, sheetConfig2, sheetConfig3, sheetConfig4)) 268 | .build(); 269 | 270 | return new ExportToExcel<>(exportType, config1); 271 | } 272 | 273 | } 274 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/configuration/ExportExcelSheetConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter.configuration; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Date; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.function.Function; 12 | 13 | import net.karneim.pojobuilder.GeneratePojoBuilder; 14 | 15 | import org.apache.poi.ss.usermodel.Font; 16 | import org.apache.poi.xssf.usermodel.XSSFCellStyle; 17 | import org.apache.poi.xssf.usermodel.XSSFFont; 18 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 19 | import org.vaadin.addons.excelexporter.utils.FormatUtil; 20 | import org.vaadin.addons.excelexporter.utils.NameGenerationUtil; 21 | 22 | /** 23 | * The Class ExportExcelSheetConfiguration is used to configure each sheet. 24 | * Several things such as report title, sheet name, component configs etc. can 25 | * also be configured 26 | * 27 | * @author Kartik Suba 28 | */ 29 | @GeneratePojoBuilder(intoPackage = "*.builder") 30 | public class ExportExcelSheetConfiguration { 31 | 32 | /** parent export excel configuration **/ 33 | private ExportExcelConfiguration exportExcelConfiguration; 34 | 35 | /** The is total row required. */ 36 | private Boolean isTotalRowRequired = Boolean.FALSE; 37 | 38 | /** The is default sheet title required. */ 39 | private Boolean isDefaultSheetTitleRequired = Boolean.TRUE; 40 | 41 | /** The is default generated by required. */ 42 | private Boolean isDefaultGeneratedByRequired = Boolean.TRUE; 43 | 44 | /** The date format. */ 45 | private String dateFormat = "EEE, dd.MM.yyyy"; 46 | 47 | /** The report title row content. */ 48 | private String reportTitleRowContent; 49 | 50 | /** The header caption start col. */ 51 | private Integer headerCaptionStartCol = 0; // default Value 52 | 53 | /** The header value start col. */ 54 | private Integer headerValueStartCol = 1; // default Value 55 | 56 | /** The no of columns in header. */ 57 | private Integer noOfColumnsInHeader = 2; // default Value 58 | 59 | /** The no of columns to merge in add header value. */ 60 | private Integer noOfColumnsToMergeInAddHeaderValue = 2; // default Value 61 | 62 | /** The no of columns in add header. */ 63 | private Integer noOfColumnsInAddHeader = 2 * this.noOfColumnsToMergeInAddHeaderValue; // default 64 | 65 | /** The is header section required. */ 66 | private Boolean isHeaderSectionRequired = Boolean.FALSE; 67 | 68 | /** The logger info row content. */ 69 | private String loggerInfoRowContent; 70 | 71 | /** The report title. */ 72 | private String reportTitle; 73 | 74 | /** The column for title region. */ 75 | private Integer[] columnForTitleRegion = new Integer[2]; 76 | 77 | /** The column for generated by region. */ 78 | private Integer[] columnForGeneratedByRegion = new Integer[2]; 79 | 80 | /** The component configs. */ 81 | private List> componentConfigs = new ArrayList<>(); 82 | 83 | /** The additional header info. */ 84 | private Map additionalHeaderInfo = new HashMap<>(); 85 | 86 | /** The sheet name. */ 87 | private String sheetname; 88 | 89 | private int frozenColumns = 0; 90 | 91 | private int frozenRows = 0; 92 | 93 | /** The report title style function. */ 94 | private Function reportTitleStyleFunction = workbook -> { 95 | XSSFCellStyle reportTitleStyle = workbook.createCellStyle(); 96 | 97 | XSSFFont boldFont = workbook.createFont(); 98 | //boldFont.setBoldweight(Font..BOLDWEIGHT_BOLD); 99 | boldFont.setBold(true); 100 | boldFont.setFontHeightInPoints((short) 14); 101 | 102 | reportTitleStyle.setFont(boldFont); 103 | 104 | return reportTitleStyle; 105 | }; 106 | 107 | /** The generated by style function. */ 108 | private Function generatedByStyleFunction = this.reportTitleStyleFunction; 109 | 110 | /** The header value style. */ 111 | private XSSFCellStyle headerValueStyle; 112 | 113 | /** The additional header caption style. */ 114 | private XSSFCellStyle additionalHeaderCaptionStyle; 115 | 116 | /** The additional header value style. */ 117 | private XSSFCellStyle additionalHeaderValueStyle; 118 | 119 | public ExportExcelConfiguration getExportExcelConfiguration() { 120 | return this.exportExcelConfiguration; 121 | } 122 | 123 | public void setExportExcelConfiguration(ExportExcelConfiguration exportExcelConfiguration) { 124 | this.exportExcelConfiguration = exportExcelConfiguration; 125 | } 126 | 127 | /** 128 | * Gets the component configs. 129 | * 130 | * @return the component configs 131 | */ 132 | public List> getComponentConfigs() { 133 | return this.componentConfigs; 134 | } 135 | 136 | /** 137 | * Sets the component configs. 138 | * 139 | * @param componentConfigs 140 | * the new component configs 141 | */ 142 | public void setComponentConfigs(final List> componentConfigs) { 143 | this.componentConfigs = componentConfigs; 144 | } 145 | 146 | /** 147 | * Gets the date format. 148 | * 149 | * @return the date format 150 | */ 151 | public String getDateFormat() { 152 | return this.dateFormat; 153 | } 154 | 155 | /** 156 | * Sets the date format. 157 | * 158 | * @param dateFormat 159 | * the new date format 160 | */ 161 | public void setDateFormat(final String dateFormat) { 162 | this.dateFormat = dateFormat; 163 | } 164 | 165 | /** 166 | * Gets the checks if is total row required. 167 | * 168 | * @return the checks if is total row required 169 | */ 170 | public Boolean getIsTotalRowRequired() { 171 | return this.isTotalRowRequired; 172 | } 173 | 174 | /** 175 | * Gets the checks if is default sheet title required. 176 | * 177 | * @return the checks if is default sheet title required 178 | */ 179 | public Boolean getIsDefaultSheetTitleRequired() { 180 | return this.isDefaultSheetTitleRequired; 181 | } 182 | 183 | /** 184 | * Gets the checks if is default generated by required. 185 | * 186 | * @return the checks if is default generated by required 187 | */ 188 | public Boolean getIsDefaultGeneratedByRequired() { 189 | return this.isDefaultGeneratedByRequired; 190 | } 191 | 192 | /** 193 | * Gets the report title row content. 194 | * 195 | * @return the report title row content 196 | */ 197 | public String getReportTitleRowContent() { 198 | if (this.reportTitleRowContent == null || this.reportTitleRowContent.isEmpty()) { 199 | return "Reportname: " + getReportTitle(); 200 | } 201 | 202 | return this.reportTitleRowContent; 203 | } 204 | 205 | /** 206 | * Gets the header caption start col. 207 | * 208 | * @return the header caption start col 209 | */ 210 | public Integer getHeaderCaptionStartCol() { 211 | return this.headerCaptionStartCol; 212 | } 213 | 214 | /** 215 | * Gets the header value start col. 216 | * 217 | * @return the header value start col 218 | */ 219 | public Integer getHeaderValueStartCol() { 220 | return this.headerValueStartCol; 221 | } 222 | 223 | /** 224 | * Gets the no of columns in header. 225 | * 226 | * @return the no of columns in header 227 | */ 228 | public Integer getNoOfColumnsInHeader() { 229 | return this.noOfColumnsInHeader; 230 | } 231 | 232 | /** 233 | * Gets the no of columns to merge in add header value. 234 | * 235 | * @return the no of columns to merge in add header value 236 | */ 237 | public Integer getNoOfColumnsToMergeInAddHeaderValue() { 238 | return this.noOfColumnsToMergeInAddHeaderValue; 239 | } 240 | 241 | /** 242 | * Gets the no of columns in add header. 243 | * 244 | * @return the no of columns in add header 245 | */ 246 | public Integer getNoOfColumnsInAddHeader() { 247 | return this.noOfColumnsInAddHeader; 248 | } 249 | 250 | /** 251 | * Gets the checks if is header section required. 252 | * 253 | * @return the checks if is header section required 254 | */ 255 | public Boolean getIsHeaderSectionRequired() { 256 | return this.isHeaderSectionRequired; 257 | } 258 | 259 | /** 260 | * Gets the logger info row content. 261 | * 262 | * @return the logger info row content 263 | */ 264 | public String getLoggerInfoRowContent() { 265 | if (this.loggerInfoRowContent == null || this.loggerInfoRowContent.isEmpty()) { 266 | return "Report generated by: " + getExportExcelConfiguration().getGeneratedBy() + " on " 267 | + FormatUtil.formatDate(new Date(), getDateFormat()); 268 | } 269 | 270 | return this.loggerInfoRowContent; 271 | } 272 | 273 | /** 274 | * Gets the report title. 275 | * 276 | * @return the report title 277 | */ 278 | public String getReportTitle() { 279 | return NameGenerationUtil.getReportTitle(this.reportTitle, getExportExcelConfiguration().getSheetConfigs() 280 | .indexOf(this) + 1); 281 | } 282 | 283 | /** 284 | * Gets the column for title region. 285 | * 286 | * @return the column for title region 287 | */ 288 | public Integer[] getColumnForTitleRegion() { 289 | if (this.columnForTitleRegion == null || this.columnForTitleRegion[0] == null) { 290 | return new Integer[] { 0, 3 }; 291 | } 292 | return this.columnForTitleRegion; 293 | } 294 | 295 | /** 296 | * Gets the column for generated by region. 297 | * 298 | * @return the column for generated by region 299 | */ 300 | public Integer[] getColumnForGeneratedByRegion() { 301 | if (this.columnForGeneratedByRegion == null || this.columnForGeneratedByRegion[0] == null) { 302 | return new Integer[] { 0, 3 }; 303 | } 304 | return this.columnForGeneratedByRegion; 305 | } 306 | 307 | /** 308 | * Gets the additional header info. 309 | * 310 | * @return the additional header info 311 | */ 312 | public Map getAdditionalHeaderInfo() { 313 | return this.additionalHeaderInfo; 314 | } 315 | 316 | /** 317 | * Gets the sheet name. 318 | * 319 | * @return the sheet name 320 | */ 321 | public String getSheetname() { 322 | return NameGenerationUtil.getSheetname(this.sheetname, getExportExcelConfiguration().getSheetConfigs() 323 | .indexOf(this) + 1); 324 | } 325 | 326 | /** 327 | * Gets the report title style function. 328 | * 329 | * @return the report title style function 330 | */ 331 | public Function getReportTitleStyleFunction() { 332 | return this.reportTitleStyleFunction; 333 | } 334 | 335 | /** 336 | * Gets the generated by style function. 337 | * 338 | * @return the generated by style function 339 | */ 340 | public Function getGeneratedByStyleFunction() { 341 | return this.generatedByStyleFunction; 342 | } 343 | 344 | /** 345 | * Gets the header value style. 346 | * 347 | * @return the header value style 348 | */ 349 | public XSSFCellStyle getHeaderValueStyle() { 350 | return this.headerValueStyle; 351 | } 352 | 353 | /** 354 | * Gets the additional header caption style. 355 | * 356 | * @return the additional header caption style 357 | */ 358 | public XSSFCellStyle getAdditionalHeaderCaptionStyle() { 359 | return this.additionalHeaderCaptionStyle; 360 | } 361 | 362 | /** 363 | * Gets the additional header value style. 364 | * 365 | * @return the additional header value style 366 | */ 367 | public XSSFCellStyle getAdditionalHeaderValueStyle() { 368 | return this.additionalHeaderValueStyle; 369 | } 370 | 371 | /** 372 | * Sets the checks if is total row required. 373 | * 374 | * @param isTotalRowRequired 375 | * the new checks if is total row required 376 | */ 377 | public void setIsTotalRowRequired(final Boolean isTotalRowRequired) { 378 | this.isTotalRowRequired = isTotalRowRequired; 379 | } 380 | 381 | /** 382 | * Sets the checks if is default sheet title required. 383 | * 384 | * @param isDefaultSheetTitleRequired 385 | * the new checks if is default sheet title required 386 | */ 387 | public void setIsDefaultSheetTitleRequired(final Boolean isDefaultSheetTitleRequired) { 388 | this.isDefaultSheetTitleRequired = isDefaultSheetTitleRequired; 389 | } 390 | 391 | /** 392 | * Sets the checks if is default generated by required. 393 | * 394 | * @param isDefaultGeneratedByRequired 395 | * the new checks if is default generated by required 396 | */ 397 | public void setIsDefaultGeneratedByRequired(final Boolean isDefaultGeneratedByRequired) { 398 | this.isDefaultGeneratedByRequired = isDefaultGeneratedByRequired; 399 | } 400 | 401 | /** 402 | * Sets the report title row content. 403 | * 404 | * @param reportTitleRowContent 405 | * the new report title row content 406 | */ 407 | public void setReportTitleRowContent(final String reportTitleRowContent) { 408 | this.reportTitleRowContent = reportTitleRowContent; 409 | } 410 | 411 | /** 412 | * Sets the header caption start col. 413 | * 414 | * @param headerCaptionStartCol 415 | * the new header caption start col 416 | */ 417 | public void setHeaderCaptionStartCol(final Integer headerCaptionStartCol) { 418 | this.headerCaptionStartCol = headerCaptionStartCol; 419 | } 420 | 421 | /** 422 | * Sets the header value start col. 423 | * 424 | * @param headerValueStartCol 425 | * the new header value start col 426 | */ 427 | public void setHeaderValueStartCol(final Integer headerValueStartCol) { 428 | this.headerValueStartCol = headerValueStartCol; 429 | } 430 | 431 | /** 432 | * Sets the no of columns in header. 433 | * 434 | * @param noOfColumnsInHeader 435 | * the new no of columns in header 436 | */ 437 | public void setNoOfColumnsInHeader(final Integer noOfColumnsInHeader) { 438 | this.noOfColumnsInHeader = noOfColumnsInHeader; 439 | } 440 | 441 | /** 442 | * Sets the no of columns to merge in add header value. 443 | * 444 | * @param noOfColumnsToMergeInAddHeaderValue 445 | * the new no of columns to merge in add header value 446 | */ 447 | public void setNoOfColumnsToMergeInAddHeaderValue(final Integer noOfColumnsToMergeInAddHeaderValue) { 448 | this.noOfColumnsToMergeInAddHeaderValue = noOfColumnsToMergeInAddHeaderValue; 449 | } 450 | 451 | /** 452 | * Sets the no of columns in add header. 453 | * 454 | * @param noOfColumnsInAddHeader 455 | * the new no of columns in add header 456 | */ 457 | public void setNoOfColumnsInAddHeader(final Integer noOfColumnsInAddHeader) { 458 | this.noOfColumnsInAddHeader = noOfColumnsInAddHeader; 459 | } 460 | 461 | /** 462 | * Sets the checks if is header section required. 463 | * 464 | * @param isHeaderSectionRequired 465 | * the new checks if is header section required 466 | */ 467 | public void setIsHeaderSectionRequired(final Boolean isHeaderSectionRequired) { 468 | this.isHeaderSectionRequired = isHeaderSectionRequired; 469 | } 470 | 471 | /** 472 | * Sets the logger info row content. 473 | * 474 | * @param loggerInfoRowContent 475 | * the new logger info row content 476 | */ 477 | public void setLoggerInfoRowContent(final String loggerInfoRowContent) { 478 | this.loggerInfoRowContent = loggerInfoRowContent; 479 | } 480 | 481 | /** 482 | * Sets the report title. 483 | * 484 | * @param reportTitle 485 | * the new report title 486 | */ 487 | public void setReportTitle(final String reportTitle) { 488 | this.reportTitle = reportTitle; 489 | } 490 | 491 | /** 492 | * Sets the column for title region. 493 | * 494 | * @param columnForTitleRegion 495 | * the new column for title region 496 | */ 497 | public void setColumnForTitleRegion(final Integer[] columnForTitleRegion) { 498 | this.columnForTitleRegion = columnForTitleRegion; 499 | } 500 | 501 | /** 502 | * Sets the column for generated by region. 503 | * 504 | * @param columnForGeneratedByRegion 505 | * the new column for generated by region 506 | */ 507 | public void setColumnForGeneratedByRegion(final Integer[] columnForGeneratedByRegion) { 508 | this.columnForGeneratedByRegion = columnForGeneratedByRegion; 509 | } 510 | 511 | /** 512 | * Sets the additional header info. 513 | * 514 | * @param additionalHeaderInfo 515 | * the additional header info 516 | */ 517 | public void setAdditionalHeaderInfo(final Map additionalHeaderInfo) { 518 | this.additionalHeaderInfo = additionalHeaderInfo; 519 | } 520 | 521 | /** 522 | * Sets the sheet name. 523 | * 524 | * @param sheetname 525 | * the new sheet name 526 | */ 527 | public void setSheetName(final String sheetname) { 528 | this.sheetname = sheetname; 529 | } 530 | 531 | /** 532 | * Sets the report title style function. 533 | * 534 | * @param reportTitleStyleFunction 535 | * the new report title style function 536 | */ 537 | public void setReportTitleStyleFunction(final Function reportTitleStyleFunction) { 538 | this.reportTitleStyleFunction = reportTitleStyleFunction; 539 | } 540 | 541 | /** 542 | * Sets the generated by style function. 543 | * 544 | * @param generatedByStyleFunction 545 | * the new generated by style function 546 | */ 547 | public void setGeneratedByStyleFunction(final Function generatedByStyleFunction) { 548 | this.generatedByStyleFunction = generatedByStyleFunction; 549 | } 550 | 551 | /** 552 | * Sets the header value style. 553 | * 554 | * @param headerValueStyle 555 | * the new header value style 556 | */ 557 | public void setHeaderValueStyle(final XSSFCellStyle headerValueStyle) { 558 | this.headerValueStyle = headerValueStyle; 559 | } 560 | 561 | /** 562 | * Sets the additional header caption style. 563 | * 564 | * @param additionalHeaderCaptionStyle 565 | * the new additional header caption style 566 | */ 567 | public void setAdditionalHeaderCaptionStyle(final XSSFCellStyle additionalHeaderCaptionStyle) { 568 | this.additionalHeaderCaptionStyle = additionalHeaderCaptionStyle; 569 | } 570 | 571 | /** 572 | * Sets the additional header value style. 573 | * 574 | * @param additionalHeaderValueStyle 575 | * the new additional header value style 576 | */ 577 | public void setAdditionalHeaderValueStyle(final XSSFCellStyle additionalHeaderValueStyle) { 578 | this.additionalHeaderValueStyle = additionalHeaderValueStyle; 579 | } 580 | 581 | public int getFrozenColumns() { 582 | return this.frozenColumns; 583 | } 584 | 585 | public void setFrozenColumns(int frozenColumns) { 586 | this.frozenColumns = frozenColumns; 587 | } 588 | 589 | public int getFrozenRows() { 590 | return this.frozenRows; 591 | } 592 | 593 | public void setFrozenRows(int frozenRows) { 594 | this.frozenRows = frozenRows; 595 | } 596 | } 597 | -------------------------------------------------------------------------------- /vaadin-excel-exporter/src/main/java/org/vaadin/addons/excelexporter/ExportToExcel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | package org.vaadin.addons.excelexporter; 5 | 6 | import java.io.File; 7 | import java.io.FileOutputStream; 8 | import java.io.IOException; 9 | import java.math.BigDecimal; 10 | import java.util.Collection; 11 | import java.util.Date; 12 | import java.util.List; 13 | import java.util.function.Function; 14 | 15 | import org.apache.poi.ss.usermodel.Cell; 16 | import org.apache.poi.ss.usermodel.Row; 17 | import org.apache.poi.ss.usermodel.Sheet; 18 | import org.apache.poi.ss.util.CellRangeAddress; 19 | import org.apache.poi.xssf.usermodel.XSSFCell; 20 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | import org.vaadin.addons.excelexporter.configuration.AbstractComponentHeaderFooterConfiguration; 24 | import org.vaadin.addons.excelexporter.configuration.ComponentFooterConfiguration; 25 | import org.vaadin.addons.excelexporter.configuration.ComponentHeaderConfiguration; 26 | import org.vaadin.addons.excelexporter.configuration.ExportExcelComponentConfiguration; 27 | import org.vaadin.addons.excelexporter.configuration.ExportExcelConfiguration; 28 | import org.vaadin.addons.excelexporter.configuration.ExportExcelSheetConfiguration; 29 | import org.vaadin.addons.excelexporter.configuration.MergedCell; 30 | import org.vaadin.addons.excelexporter.model.ExportType; 31 | import org.vaadin.addons.excelexporter.utils.ExcelStyleUtil; 32 | import org.vaadin.addons.excelexporter.utils.NameGenerationUtil; 33 | import org.vaadin.addons.excelexporter.utils.FormatUtil; 34 | 35 | import com.vaadin.data.provider.ListDataProvider; 36 | import com.vaadin.ui.Grid; 37 | import com.vaadin.ui.components.grid.FooterRow; 38 | import com.vaadin.ui.components.grid.HeaderRow; 39 | 40 | /** 41 | * The Class ExportToExcelUtility is the core algorithm that generates Excel 42 | * based on the configurations. 43 | * 44 | * @author Kartik Suba 45 | * @param 46 | * the generic type 47 | */ 48 | public class ExportToExcel extends AbstractExportTo { 49 | 50 | /** The Constant LOGGER. */ 51 | private static final Logger LOGGER = LoggerFactory.getLogger(ExportToExcel.class); 52 | 53 | /** The excel mime type. */ 54 | private static String EXCEL_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 55 | 56 | /** The workbook. */ 57 | protected XSSFWorkbook workbook; 58 | 59 | /** The export excel configuration. */ 60 | protected final ExportExcelConfiguration exportExcelConfiguration; 61 | 62 | /** The resultant export type. */ 63 | protected final ExportType exportType; 64 | 65 | /** 66 | * Gets the resultant export type. 67 | * 68 | * @return the resultant export type 69 | */ 70 | public ExportType getResultantExportType() { 71 | return this.exportType; 72 | } 73 | 74 | /************************************** Constructors *********************************************************/ 75 | 76 | /** 77 | * Instantiates a new export to excel utility. 78 | * 79 | * @param exportType 80 | * the export type 81 | * @param exportExcelConfiguration 82 | * the export excel configuration 83 | */ 84 | public ExportToExcel(final ExportType exportType, 85 | final ExportExcelConfiguration exportExcelConfiguration) { 86 | super(EXCEL_MIME_TYPE); 87 | this.exportType = exportType; 88 | this.exportExcelConfiguration = exportExcelConfiguration; 89 | this.workbook = new XSSFWorkbook(); 90 | 91 | process(this.workbook, exportExcelConfiguration.getSheetConfigs()); 92 | } 93 | 94 | /************************************* Constructors *********************************************************/ 95 | 96 | /************************************** 97 | * Pre-processing and Book-keeping Information 98 | *************************/ 99 | 100 | /** 101 | * This method processes the sheet configs 102 | * 103 | * @param workbook 104 | * @param sheetConfigs 105 | * 106 | */ 107 | protected void process(XSSFWorkbook workbook, List> sheetConfigs) { 108 | for (ExportExcelSheetConfiguration sheetConfig : sheetConfigs) { 109 | Sheet sheet = workbook.createSheet(sheetConfig.getSheetname()); 110 | sheet.setAutobreaks(true); 111 | 112 | int rowNum = 0; 113 | rowNum = addSheetTitle(workbook, sheetConfig, sheet, rowNum); 114 | rowNum = addSheetGeneratedBy(workbook, sheetConfig, sheet, rowNum); 115 | addComponents(workbook, sheetConfig, sheet, rowNum); 116 | } 117 | } 118 | 119 | private void addComponents(XSSFWorkbook workbook, ExportExcelSheetConfiguration sheetConfig, Sheet sheet, 120 | int rowNum) { 121 | int tmpRowNum = rowNum; 122 | for (ExportExcelComponentConfiguration componentConfig : sheetConfig.getComponentConfigs()) { 123 | if (componentConfig.getGrid() != null) { 124 | tmpRowNum = addGridToExcelSheet(componentConfig.getGrid(), workbook, sheet, tmpRowNum, sheetConfig, 125 | componentConfig); 126 | } 127 | } 128 | } 129 | 130 | private int addSheetGeneratedBy(XSSFWorkbook workbook, ExportExcelSheetConfiguration sheetConfig, 131 | Sheet sheet, int rowNum) { 132 | int tmpRowNum = rowNum; 133 | if (sheetConfig.getIsDefaultGeneratedByRequired()) { 134 | // Adding an empty row before generated by 135 | Row myHeaderRow2 = sheet.createRow(tmpRowNum++); 136 | Cell myHeaderCell2 = myHeaderRow2.createCell(0); 137 | myHeaderCell2.setCellValue(sheetConfig.getLoggerInfoRowContent()); 138 | myHeaderCell2.setCellStyle(sheetConfig.getGeneratedByStyleFunction() 139 | .apply(workbook)); 140 | sheet.addMergedRegion(new CellRangeAddress(tmpRowNum, tmpRowNum, 141 | sheetConfig.getColumnForGeneratedByRegion()[0], sheetConfig.getColumnForGeneratedByRegion()[1])); 142 | } 143 | return tmpRowNum; 144 | } 145 | 146 | private int addSheetTitle(XSSFWorkbook workbook, ExportExcelSheetConfiguration sheetConfig, Sheet sheet, 147 | int rowNum) { 148 | int tmpRowNum = rowNum; 149 | if (sheetConfig.getIsDefaultSheetTitleRequired()) { 150 | // Creating Report Name Row 151 | Row myHeaderRow1 = sheet.createRow(tmpRowNum++); 152 | Cell myHeaderCell1 = myHeaderRow1.createCell(0); 153 | 154 | myHeaderCell1.setCellValue(sheetConfig.getReportTitleRowContent()); 155 | myHeaderCell1.setCellStyle(sheetConfig.getReportTitleStyleFunction() 156 | .apply(workbook)); 157 | sheet.addMergedRegion(new CellRangeAddress(tmpRowNum, tmpRowNum, sheetConfig.getColumnForTitleRegion()[0], 158 | sheetConfig.getColumnForTitleRegion()[1])); 159 | } 160 | return tmpRowNum; 161 | } 162 | 163 | /************************************* 164 | * Adding Grid To Sheet 165 | *******************************************/ 166 | 167 | /** 168 | * Creates the grid content. 169 | * 170 | * @param grid 171 | * the grid 172 | * @param myWorkBook 173 | * the my work book 174 | * @param sheet 175 | * the sheet 176 | * @param rowNum 177 | * current rownum 178 | * @param sheetConfiguration 179 | * the sheet configuration 180 | * @param componentConfiguration 181 | * the component configuration 182 | * @return the integer 183 | */ 184 | @SuppressWarnings("unchecked") 185 | protected Integer addGridToExcelSheet(final Grid grid, final XSSFWorkbook myWorkBook, Sheet sheet, 186 | int rowNum, final ExportExcelSheetConfiguration sheetConfiguration, 187 | final ExportExcelComponentConfiguration componentConfiguration) { 188 | 189 | Collection items; 190 | if (grid.getDataProvider() instanceof ListDataProvider) { 191 | items = ((ListDataProvider) grid.getDataProvider()).getItems(); 192 | } else { 193 | throw new UnsupportedOperationException("dataProvider " + grid.getDataProvider() 194 | .getClass() + " of grid is not supported"); 195 | } 196 | 197 | return addGridToExcelSheet(items, myWorkBook, sheet, rowNum, sheetConfiguration, componentConfiguration); 198 | } 199 | 200 | /** 201 | * Creates the generic content. Adds the component header, data, and footer 202 | * sections 203 | * 204 | * @param itemIds 205 | * the item ids 206 | * @param myWorkBook 207 | * the my work book 208 | * @param sheet 209 | * the sheet 210 | * @param rowNum 211 | * current rownum 212 | * @param sheetConfiguration 213 | * the sheet configuration 214 | * @param componentConfiguration 215 | * the component configuration 216 | * @return the integer 217 | */ 218 | protected int addGridToExcelSheet(final Collection itemIds, final XSSFWorkbook myWorkBook, Sheet sheet, 219 | int rowNum, final ExportExcelSheetConfiguration sheetConfiguration, 220 | final ExportExcelComponentConfiguration componentConfiguration) { 221 | 222 | int tmpRowNum = rowNum; 223 | // create space before each grid 224 | tmpRowNum++; 225 | 226 | sheet.setRowBreak(tmpRowNum); 227 | 228 | sheet.createFreezePane(sheetConfiguration.getFrozenColumns(), sheetConfiguration.getFrozenRows()); 229 | 230 | tmpRowNum = addGridHeaderRows(sheet, tmpRowNum, componentConfiguration); 231 | tmpRowNum = addGridContent(itemIds, myWorkBook, sheet, tmpRowNum, sheetConfiguration, componentConfiguration); 232 | tmpRowNum = addGridFooterRows(sheet, tmpRowNum, componentConfiguration); 233 | 234 | // Disabling auto columns for each column 235 | for (int columns = 0; columns < componentConfiguration.getVisibleProperties().length; columns++) { 236 | sheet.autoSizeColumn(columns, false); 237 | } 238 | 239 | return tmpRowNum; 240 | } 241 | 242 | private int addGridContent(final Collection itemIds, final XSSFWorkbook myWorkBook, Sheet sheet, 243 | int rowNum, final ExportExcelSheetConfiguration sheetConfiguration, 244 | final ExportExcelComponentConfiguration componentConfiguration) { 245 | int tmpRowNum = rowNum; 246 | int dataRowContentStart = rowNum; 247 | for (final BEANTYPE itemId : itemIds) { 248 | addGridDataRow( myWorkBook, sheet, sheetConfiguration, componentConfiguration, itemId, tmpRowNum, 249 | dataRowContentStart); 250 | tmpRowNum++; 251 | } 252 | return tmpRowNum; 253 | } 254 | 255 | /** 256 | * Adds the generic header rows as configured in the component configuration 257 | * 258 | * @param sheet 259 | * the sheet 260 | * @param rowNum 261 | * current rownum 262 | * 263 | * @param componentConfiguration 264 | * the component configuration 265 | * @return the integer 266 | */ 267 | protected Integer addGridHeaderRows(Sheet sheet, int rowNum, 268 | final ExportExcelComponentConfiguration componentConfiguration) { 269 | if (componentConfiguration.getHeaderConfigs() == null) { 270 | return rowNum; 271 | } 272 | 273 | int tmpRowNum = rowNum; 274 | 275 | for (ComponentHeaderConfiguration headerConfig : componentConfiguration.getHeaderConfigs()) { 276 | tmpRowNum = addHeaderFooterRow(sheet, tmpRowNum, componentConfiguration, headerConfig); 277 | } 278 | 279 | // Add All the headers 280 | return tmpRowNum; 281 | } 282 | 283 | @SuppressWarnings({ "rawtypes", "unchecked" }) 284 | private int addHeaderFooterRow(Sheet sheet, int rowNum, 285 | final ExportExcelComponentConfiguration componentConfiguration, 286 | AbstractComponentHeaderFooterConfiguration headerFooterConfig) { 287 | int tmpRowNum = rowNum; 288 | 289 | Row myRow = sheet.createRow(tmpRowNum); 290 | 291 | int startMerge = -999; 292 | for (int columns = 0; columns < componentConfiguration.getVisibleProperties().length; columns++) { 293 | Cell myCell = myRow.createCell(columns, XSSFCell.CELL_TYPE_STRING); 294 | String columnId = componentConfiguration.getVisibleProperties()[columns]; 295 | if (headerFooterConfig.getMergedCells() != null) { 296 | startMerge = addMergedCell( sheet, tmpRowNum, componentConfiguration, headerFooterConfig, startMerge, 297 | columns, myCell); 298 | } else if (headerFooterConfig.getRow() != null) { 299 | if (headerFooterConfig.getRow() instanceof HeaderRow) { 300 | ExcelStyleUtil.addGenericGridHeaderRow( ((HeaderRow) headerFooterConfig.getRow()).getCell(columnId), 301 | myCell); 302 | } else if (headerFooterConfig.getRow() instanceof FooterRow) { 303 | ExcelStyleUtil.addGenericGridFooterRow( ((FooterRow) headerFooterConfig.getRow()).getCell(columnId), 304 | myCell); 305 | } 306 | } else if (headerFooterConfig.getColumnKeys() != null) { 307 | myCell.setCellValue(headerFooterConfig.getColumnKeys()[columns]); 308 | } 309 | myCell.setCellStyle(componentConfiguration.getHeaderStyleFunction() 310 | .apply(this.workbook, columnId)); 311 | } 312 | 313 | if (headerFooterConfig instanceof ComponentHeaderConfiguration 314 | && ((ComponentHeaderConfiguration) headerFooterConfig).isAutoFilter()) { 315 | sheet.setAutoFilter(new CellRangeAddress(tmpRowNum, tmpRowNum, 0, 316 | componentConfiguration.getVisibleProperties().length - 1)); 317 | } 318 | 319 | tmpRowNum++; 320 | return tmpRowNum; 321 | } 322 | 323 | private int addMergedCell(Sheet sheet, int rowNum, 324 | final ExportExcelComponentConfiguration componentConfiguration, 325 | AbstractComponentHeaderFooterConfiguration headerFooterConfig, int startMerge, int columns, 326 | Cell myCell) { 327 | int tmpStartMerge = startMerge; 328 | for (MergedCell joinedHeader : headerFooterConfig.getMergedCells()) { 329 | if (joinedHeader.getStartProperty() 330 | .equalsIgnoreCase(String.valueOf(componentConfiguration.getVisibleProperties()[columns]))) { 331 | tmpStartMerge = columns; 332 | myCell.setCellValue(joinedHeader.getHeaderKey()); 333 | } else if (joinedHeader.getEndProperty() 334 | .equalsIgnoreCase(String.valueOf(componentConfiguration.getVisibleProperties()[columns]))) { 335 | int endMerge = columns; 336 | sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, tmpStartMerge, endMerge)); 337 | } 338 | } 339 | sheet.autoSizeColumn(columns, false); 340 | return tmpStartMerge; 341 | } 342 | 343 | /** 344 | * Adds the generic footer rows as configured in the component configuration 345 | * 346 | * @param sheet 347 | * the sheet 348 | * @param rowNum 349 | * current rownum 350 | * @param componentConfiguration 351 | * the component configuration 352 | * @return the integer 353 | */ 354 | protected Integer addGridFooterRows(Sheet sheet, int rowNum, 355 | final ExportExcelComponentConfiguration componentConfiguration) { 356 | if (componentConfiguration.getFooterConfigs() == null) { 357 | return rowNum; 358 | } 359 | 360 | int tmpRowNum = rowNum; 361 | for (ComponentFooterConfiguration footerConfig : componentConfiguration.getFooterConfigs()) { 362 | tmpRowNum = addHeaderFooterRow(sheet, tmpRowNum, componentConfiguration, footerConfig); 363 | } 364 | 365 | return tmpRowNum; 366 | } 367 | 368 | /** 369 | * Adds the generic data row. Applies formatting to the cells as configured. 370 | * 371 | * @param myWorkBook 372 | * the my work book 373 | * @param sheet 374 | * the sheet 375 | * @param rowNum 376 | * current rownum 377 | * @param sheetConfiguration 378 | * the sheet configuration 379 | * @param componentConfiguration 380 | * the component configuration 381 | * @param itemId 382 | * the item id 383 | * @param rowNum 384 | * the local row 385 | * @param dataRowContentStart 386 | */ 387 | protected void addGridDataRow(final XSSFWorkbook myWorkBook, Sheet sheet, 388 | final ExportExcelSheetConfiguration sheetConfiguration, 389 | final ExportExcelComponentConfiguration componentConfiguration, final BEANTYPE itemId, 390 | final Integer rowNum, int dataRowContentStart) { 391 | 392 | Row myRow = sheet.createRow(rowNum); 393 | try { 394 | 395 | for (int columns = 0; columns < componentConfiguration.getVisibleProperties().length; columns++) { 396 | String columnId = componentConfiguration.getVisibleProperties()[columns]; 397 | Function function = componentConfiguration.getGrid() 398 | .getColumn(columnId) 399 | .getValueProvider(); 400 | 401 | Object value = function.apply(itemId); 402 | Cell myCell = myRow.createCell(columns, XSSFCell.CELL_TYPE_STRING); 403 | 404 | myCell.setCellStyle(componentConfiguration.getContentStyleFunction() 405 | .apply(myWorkBook, columnId, value, rowNum - dataRowContentStart)); 406 | 407 | if (value == null) { 408 | myCell.setCellValue(""); 409 | continue; 410 | } 411 | 412 | setCellValueBasedOnValueDataType( sheetConfiguration, componentConfiguration, itemId, columns, value, 413 | myCell); 414 | 415 | } 416 | } catch (Exception e) { 417 | ExportToExcel.LOGGER.error("addGenericDataRow throws + " + e.getMessage(), e); 418 | } 419 | } 420 | 421 | private void setCellValueBasedOnValueDataType(final ExportExcelSheetConfiguration sheetConfiguration, 422 | final ExportExcelComponentConfiguration componentConfiguration, final BEANTYPE itemId, 423 | int columns, Object value, Cell myCell) { 424 | // Date 425 | if (componentConfiguration.getDateFormattingProperties() 426 | .contains(String.valueOf(componentConfiguration.getVisibleProperties()[columns]))) { 427 | myCell.setCellValue(FormatUtil.formatDate((Date) value, sheetConfiguration.getDateFormat())); 428 | return; 429 | } 430 | 431 | // Integer 432 | if (componentConfiguration.getIntegerFormattingProperties() 433 | .contains(String.valueOf(componentConfiguration.getVisibleProperties()[columns]))) { 434 | 435 | String formattedInteger = FormatUtil.localizedFormat(value != null && !String.valueOf(value) 436 | .isEmpty() ? String.valueOf(value) : null, Boolean.TRUE); 437 | String customFormattedString = FormatUtil 438 | .applyColumnFormatter( componentConfiguration.getVisibleProperties(), componentConfiguration, itemId, 439 | columns, formattedInteger); 440 | myCell.setCellValue(customFormattedString != null ? customFormattedString : formattedInteger); 441 | return; 442 | } 443 | 444 | // Float 445 | if (componentConfiguration.getFloatFormattingProperties() 446 | .contains(String.valueOf(componentConfiguration.getVisibleProperties()[columns]))) { 447 | setCellValueBasedOnFloat(componentConfiguration, itemId, columns, value, myCell); 448 | return; 449 | } 450 | 451 | // Boolean 452 | if (componentConfiguration.getBooleanFormattingProperties() 453 | .contains(String.valueOf(componentConfiguration.getVisibleProperties()[columns]))) { 454 | String customFormattedString = FormatUtil 455 | .applyColumnFormatter( componentConfiguration.getVisibleProperties(), componentConfiguration, itemId, 456 | columns, Boolean.valueOf((boolean) value)); 457 | myCell.setCellValue(customFormattedString != null ? customFormattedString : value.toString()); 458 | return; 459 | } 460 | 461 | String customFormattedString = FormatUtil.applyColumnFormatter( componentConfiguration.getVisibleProperties(), 462 | componentConfiguration, itemId, columns, value); 463 | myCell.setCellValue(customFormattedString != null ? customFormattedString : value.toString()); 464 | } 465 | 466 | private void setCellValueBasedOnFloat(final ExportExcelComponentConfiguration componentConfiguration, 467 | final BEANTYPE itemId, int columns, Object value, Cell myCell) { 468 | if (value instanceof Double) { 469 | 470 | String formattedDouble = FormatUtil.formatFloat((Double) value); 471 | String customFormattedString = FormatUtil 472 | .applyColumnFormatter( componentConfiguration.getVisibleProperties(), componentConfiguration, itemId, 473 | columns, formattedDouble); 474 | myCell.setCellValue(customFormattedString != null ? customFormattedString : formattedDouble); 475 | } else if (value instanceof BigDecimal) { 476 | String formattedBigDecimal = FormatUtil.formatFloat(((BigDecimal) value).doubleValue()); 477 | String customFormattedString = FormatUtil 478 | .applyColumnFormatter( componentConfiguration.getVisibleProperties(), componentConfiguration, itemId, 479 | columns, formattedBigDecimal); 480 | myCell.setCellValue(customFormattedString != null ? customFormattedString : formattedBigDecimal); 481 | } 482 | } 483 | 484 | /************************************ 485 | * Generic Code to add Content and Header Section 486 | *******************************************/ 487 | 488 | /** 489 | * Generate report file. 490 | * 491 | * @return the file 492 | */ 493 | @Override 494 | protected File generateReportFile() { 495 | 496 | File tempFile = null; 497 | 498 | FileOutputStream fileOut = null; 499 | try { 500 | tempFile = File.createTempFile("tmp", "." + this.exportType.getExtension()); 501 | fileOut = new FileOutputStream(tempFile); 502 | this.workbook.write(fileOut); 503 | } catch (final IOException e) { 504 | LOGGER.warn("Converting to XLS failed with IOException " + e); 505 | return null; 506 | } finally { 507 | if (tempFile != null) { 508 | tempFile.deleteOnExit(); 509 | } 510 | try { 511 | if (fileOut != null) { 512 | fileOut.close(); 513 | } 514 | } catch (final IOException e) { 515 | LOGGER.warn("Closing file to XLS failed with IOException " + e); 516 | } 517 | } 518 | 519 | return tempFile; 520 | } 521 | 522 | /** 523 | * Export the workbook to the end-user. 524 | * 525 | * Code obtained from: 526 | * http://vaadin.com/forum/-/message_boards/view_message/159583 527 | * 528 | * @return true, if successful 529 | */ 530 | @Override 531 | protected boolean sendConverted(File file) { 532 | return super.sendConvertedFileToUser(file, NameGenerationUtil 533 | .getFilename( this.exportExcelConfiguration.getExportFileName(), 534 | this.exportExcelConfiguration.getMaxFilenameCalendarExtension(), this.exportType)); 535 | } 536 | 537 | } 538 | --------------------------------------------------------------------------------