DsExcel Java supports the JSON I/O of SpreadJS files. You can also import an ssjson file created with SpreadJS Designer and save it back after modifying it as per your preferences.
The below example code loads an ssjson file and then saves it to xlsx format.
Java |
Copy Code |
---|---|
// Create a new workbook Workbook workbook = new Workbook(); // Load SSJSON file try { FileInputStream stream = new FileInputStream("test.ssjson"); workbook.fromJson(stream); } catch (Exception e) { e.getMessage(); } // Save file workbook.save("workbook-ssjson.xlsx"); |
Note: Upon loading the SpreadJS JSON file, if users get the getColorIndex method of the IBorder interface in order to set an index color, it will return a valid value only if the getColor method of the IBorder interface is set to any rgb color; else, it will return -2 as an invalid flag. Usually, an index color can be converted to rgb color but vice a versa is not possible.
DsExcel Java allows you to perform JSON I/O of SpreadJS files containing shapes. You can also download the JSON file containing shape from here.
DsExcel supports JSON I/O and PDF export of SpreadJS files containing barcodes. However while exporting to PDF, partial SpreadJS barcode properties are supported. To know more about unsupported properties, refer Export Barcodes.
You can also download the JSON file containing barcodes from here.
SpreadJS files containing cell buttons are supported by DsExcel for JSON I/O, HTML, image and PDF exporting. You can also download the JSON file containing cell buttons from here.
DsExcel supports JSON I/O of SpreadJS files containing cell dropdowns like calculator, color picker, time picker etc. You can also download the JSON file containing cell dropdowns from here.
DsExcel supports JSON I/O of SpreadJS files containing form controls like button, dropdown, checkbox, etc., allowing you to import and export form controls to an ssjson file. You can also download the JSON file containing form controls from here.
Validation styles can be used to highlight invalid data in a worksheet. DsExcel supports JSON I/O, image and PDF exporting of SpreadJS files containing validation styles. You can also download the JSON file containing validation style from here.
When text in a cell is longer than the column width, SpreadJS allows you to show ellipsis instead of overflowing text in the other cell. The SpreadJS files containing text ellipsis are supported for JSON I/O and PDF exporting in DsExcel. You can also download the JSON file containing text ellipsis from here.
Limitation
SpreadJS allows different types of text alignment composed with text ellipsis but DsExcel does not. Hence, text ellipsis is only shown at the end of text in exported PDF.
In SpreadJS, you can create a range cell type which can be used to specify a cell range in the worksheet as a template. You can modify the display mode and appearance of the resultant data just by changing the template. DsExcel supports JSON I/O and PDF exporting of SpreadJS files containing Range templates.
You can also download the JSON file containing range template from here.
SpreadJS supports Format string feature which allows cells to have both formulas and text as a part of text value templates. DsExcel supports JSON I/O of SpreadJS files containing format strings.
You can also download the JSON file containing format string from here.
In SpreadJS, while importing or exporting custom data from or to a JSON object, you can set several serialization or deserialization options. DsExcel API supports some of these options for workbook and worksheet JSON I/O. The below table explains the supported options in SpreadJS and DsExcel.
SpreadJS (toJSON and fromJSON) | DsExcel (toJSON and fromJSON) | |
---|---|---|
Serialization |
ignoreStyle ignoreFormula rowHeadersAsFrozenColumns columnHeadersAsFrozenRows |
ignoreStyle ignoreFormula IgnoreColumnRowInfoOutOfUsedRange IgnoreColumnRowInfoOutOfUsedRange IgnoreRangeOutOfRowColumnCount IgnoreRangeOutOfRowColumnCount ExportSharedFormula |
Deserialization |
ignoreStyle ignoreFormula frozenColumnsAsRowHeaders frozenRowsAsColumnHeaders doNotRecalculateAfterLoad |
ignoreStyle ignoreFormula doNotRecalculateAfterLoad |
DsExcel provides SerializationOptions and DeserializationOptions classes in API with above-mentioned supported properties.
The following example code serializes a workbook to JSON with options in DsExcel.
Java |
Copy Code |
---|---|
// Ignore style and formula when deserialize workbook from json. DeserializationOptions deserializationOptions = new DeserializationOptions(); deserializationOptions.setIgnoreStyle(true); deserializationOptions.setIgnoreFormula(true); workbook.fromJson(json, deserializationOptions); // Save to an excel file workbook.save("FromJsonWithOptions.xlsx"); |
The following example code deserializes a workbook from JSON with options in DsExcel.
Java |
Copy Code |
---|---|
// Ignore style and formula when serialize workbook to json. SerializationOptions serializationOptions = new SerializationOptions(); serializationOptions.setIgnoreStyle(true); serializationOptions.setIgnoreFormula(true); String jsonWithOption = workbook.toJson(serializationOptions); workbook.fromJson(jsonWithOption); // Save to an excel file workbook.save("ToJsonWithOptions.xlsx"); |
You can control the size of exported JSON file by choosing whether you want to keep the style and size of rows and columns which are out of the used range. The setIgnoreColumnRowInfoOutOfUsedRange method is provided in SerializationOptions class which:
The following example code shows how the size of JSON file is impacted by setting the above mentioned method.
Java |
Copy Code |
---|---|
Workbook book = new Workbook(); IWorksheet worksheet = book.getWorksheets().get(0); //Add custom name style. IStyle style = book.getStyles().add("testStyle1"); style.getFont().setThemeColor(ThemeColor.Accent1); style.getFont().setTintAndShade(0.8); style.getFont().setItalic(true); style.getFont().setBold(true); style.getFont().setName("LiSu"); style.getFont().setSize(28); style.getFont().setStrikethrough(true); style.getFont().setSubscript(true); style.getFont().setSuperscript(false); style.getFont().setUnderline(UnderlineType.Double); Object data = new Object[][]{ {"test", "test", "test", "test" }, {"test", "test", "test", "test" }, {"test", "test", "test", "test" }, {"test", "test", "test", "test" }, {"test", "test", "test", "test" }, }; worksheet.getRange("B2:E6").setValue(data); worksheet.getRange("A:XFD").setStyle(style); worksheet.getRange("A:XFD").setColumnWidthInPixel(20); //Export sizes/styles of only used range to json SerializationOptions options = new SerializationOptions(); options.setIgnoreColumnRowInfoOutOfUsedRange(true); try { book.toJson(new FileOutputStream("TestJson_true.json"), options); // Size of output file is 9KB } catch (FileNotFoundException e1) { e1.printStackTrace(); } //Export all sizes/styles to json SerializationOptions options2 = new SerializationOptions(); options2.setIgnoreColumnRowInfoOutOfUsedRange(false); try { book.toJson(new FileOutputStream("TestJson_false.json"), options2); // Size of output file is 809KB } catch (FileNotFoundException e1) { e1.printStackTrace(); } //Default behavior (same as true option) try { book.toJson(new FileOutputStream("TestJson_default.json")); // Size of output file is 9KB } catch (FileNotFoundException e) { e.printStackTrace(); } |
You can also control whether to export formulas as shared formulas when exporting to a JSON file using the setExportSharedFormula method in SerializationOptions class. This enables you to export the formulas as shared formulas when it is set to true (the default value). However, if the value is set to false, the formulas will be exported as individual formulas.
In DsExcel v6.0.1 and higher versions, the formula is exported as a shared formula to a JSON file (or SSJSON file). Because the shared formula is not compatible with DsExcel versions less than or equal to v5 and SpreadJS versions less than or equal to v15, you can use this option for backward compatibility and skip shared formulas in the exported JSON file.
The following example code exports formulas as shared formulas:
Java |
Copy Code |
---|---|
// Create a new workbook. var workbook = new Workbook(); // Set options for iterative calculation. workbook.getOptions().getFormulas().setEnableIterativeCalculation(true); workbook.getOptions().getFormulas().setMaximumIterations(20); var worksheet = workbook.getWorksheets().get(0); // Set values and formulas. worksheet.getRange("B2").setValue("Initial Cash"); worksheet.getRange("C2").setValue(10000); worksheet.getRange("B3").setValue("Interest"); worksheet.getRange("C3").setValue(0.0125); worksheet.getRange("B5").setValue("Month"); worksheet.getRange("C5").setValue("Total Cash"); worksheet.getRange("B6:B17").setValue(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }); worksheet.getRange("C6").setFormula("=C2*(1+$C$3)"); worksheet.getRange("C7:C17").setFormula("=C6*(1+$C$3)"); // Initialize SerializationOptions and set ExportSharedFormula to true. SerializationOptions options = new SerializationOptions(); options.setExportSharedFormula(true); // Save the JSON file. PrintWriter out1; try { out1 = new PrintWriter("ExportSharedFormulas.json"); out1.println(workbook.toJson(options)); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Initialize SerializationOptions and set ExportSharedFormula to false. SerializationOptions options2 = new SerializationOptions(); options2.setExportSharedFormula(false); // Save the JSON file. PrintWriter out2; try { out2 = new PrintWriter("ExportIndividualFormulas.json"); out2.println(workbook.toJson(options)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } |
Note: SpreadJS supports multi-level row or column headers but DsExcel does not. However, you can still retain the header information in DsExcel by following the below steps:
DsExcel supports JSON I/O and PDF exporting of SpreadJS files containing checkbox list and radiobutton list cell types. You can also download the JSON file containing radiobutton list and checkbox list cell type from here.
DsExcel also provides RadioButtonListCellType and CheckBoxListCellType classes in its API to add these cell types.
The following example code creates a checkbox list cell type for a cell in DsExcel.
Java |
Copy Code |
---|---|
//create a new workbook Workbook workbook = new Workbook(); IWorksheet worksheet = workbook.getWorksheets().get(0); CheckBoxListCellType cellType = new CheckBoxListCellType(); cellType.setDirection(CellTypeDirection.Horizontal); cellType.setTextAlign(CellTypeTextAlign.Right); cellType.setIsFlowLayout(false); cellType.setMaxColumnCount(2); cellType.setMaxRowCount(1); cellType.setHorizontalSpacing(20); cellType.setVerticalSpacing(5); cellType.getItems().add(new SelectFieldItem("sample1", "1")); cellType.getItems().add(new SelectFieldItem("sample2", "2")); cellType.getItems().add(new SelectFieldItem("sample3", "3")); cellType.getItems().add(new SelectFieldItem("sample4", "4")); cellType.getItems().add(new SelectFieldItem("sample5", "5")); worksheet.getRange("A1").setRowHeight(60); worksheet.getRange("A1").setColumnWidth(25); worksheet.getRange("A1").setCellType(cellType); //check multiple options in the check box list worksheet.getRange("A1").setValue(new Object[][]{ {new Object[]{"1", "3", "5"}} }); //save to an pdf file workbook.save("AddCheckBoxListCellType.pdf"); |
The following example code creates checkbox list cell type and sets the value of the option as a custom object.
Java |
Copy Code |
---|---|
//create a new workbook Workbook workbook = new Workbook(); Workbook.setValueJsonSerializer(new CustomObjectJsonSerializer()); IWorksheet worksheet = workbook.getWorksheets().get(0); CheckBoxListCellType cellType = new CheckBoxListCellType(); cellType.setDirection(CellTypeDirection.Horizontal); cellType.setTextAlign(CellTypeTextAlign.Right); cellType.setIsFlowLayout(false); cellType.setMaxColumnCount(2); cellType.setMaxRowCount(1); cellType.setHorizontalSpacing(20); cellType.setVerticalSpacing(5); cellType.getItems().add(new SelectFieldItem("player1", new People(5, "Tom"))); cellType.getItems().add(new SelectFieldItem("player2", new People(5, "Jerry"))); cellType.getItems().add(new SelectFieldItem("player3", new People(6, "Mario"))); cellType.getItems().add(new SelectFieldItem("player4", new People(4, "Luigi"))); worksheet.getRange("A1").setRowHeight(40); worksheet.getRange("A1").setColumnWidth(25); worksheet.getRange("A1").setCellType(cellType); worksheet.getRange("A1").setValue(new Object[][]{ {new Object[]{new People(5, "Tom"), new People(6, "Mario")}} }); //save to an pdf file workbook.save("AddCheckBoxListCellTypeCustomObject.pdf"); } class CustomObjectJsonSerializer implements IJsonSerializer { Gson gson = new Gson(); public final Object deserialize(String json) { return this.gson.fromJson(json, JsonElement.class); } public final String serialize(Object value) { return this.gson.toJson(value); } } class People { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public People(int age, String name){ this.age = age; this.name = name; } @Override public boolean equals(Object obj){ return obj instanceof People && age == ((People)obj).getAge() && name.equals(((People)obj).getName()); } @Override public int hashCode() { int hashCode = 17; hashCode = 31 * hashCode + this.age; hashCode = 31 * hashCode + (this.name == null ? 0 : this.name.hashCode()); return hashCode; } } |
The following example code creates a radio list cell type for a cell in DsExcel.
Java |
Copy Code |
---|---|
//create a new workbook Workbook workbook = new Workbook(); IWorksheet worksheet = workbook.getWorksheets().get(0); RadioButtonListCellType cellType = new RadioButtonListCellType(); cellType.setDirection(CellTypeDirection.Horizontal); cellType.setTextAlign(CellTypeTextAlign.Right); cellType.setIsFlowLayout(false); cellType.setMaxColumnCount(2); cellType.setMaxRowCount(1); cellType.setHorizontalSpacing(20); cellType.setVerticalSpacing(5); cellType.getItems().add(new SelectFieldItem("sample1", "1")); cellType.getItems().add(new SelectFieldItem("sample2", "2")); cellType.getItems().add(new SelectFieldItem("sample3", "3")); cellType.getItems().add(new SelectFieldItem("sample4", "4")); cellType.getItems().add(new SelectFieldItem("sample5", "5")); worksheet.getRange("A1").setRowHeight(60); worksheet.getRange("A1").setColumnWidth(25); worksheet.getRange("A1").setCellType(cellType); worksheet.getRange("A1").setValue("1"); //check multiple options in the radio button list worksheet.getRange("A1").setValue(new Object[][]{ { new Object[]{"1", "3", "5"}} }); //save to an pdf file workbook.save("AddRadioListCellType.pdf"); |
The following example code creates radiobutton cell type and sets the value of the option as a custom object.
Java |
Copy Code |
---|---|
//create a new workbook Workbook workbook = new Workbook(); Workbook.setValueJsonSerializer(new CustomObjectJsonSerializer()); IWorksheet worksheet = workbook.getWorksheets().get(0); RadioButtonListCellType cellType = new RadioButtonListCellType(); cellType.setDirection(CellTypeDirection.Horizontal); cellType.setTextAlign(CellTypeTextAlign.Right); cellType.setIsFlowLayout(false); cellType.setMaxColumnCount(2); cellType.setMaxRowCount(1); cellType.setHorizontalSpacing(20); cellType.setVerticalSpacing(5); cellType.getItems().add(new SelectFieldItem("player1", new People(5, "Tom"))); cellType.getItems().add(new SelectFieldItem("player2", new People(5, "Jerry"))); cellType.getItems().add(new SelectFieldItem("player3", new People(6, "Mario"))); cellType.getItems().add(new SelectFieldItem("player4", new People(4, "Luigi"))); worksheet.getRange("A1").setRowHeight(40); worksheet.getRange("A1").setColumnWidth(25); worksheet.getRange("A1").setCellType(cellType); worksheet.getRange("A1").setValue(new People(6, "Mario")); //save to an pdf file workbook.save("AddRadioButtonCellTypeCustomObject.pdf"); } class CustomObjectJsonSerializer implements IJsonSerializer { Gson gson = new Gson(); public final Object deserialize(String json) { return this.gson.fromJson(json, JsonElement.class); } public final String serialize(Object value) { return this.gson.toJson(value); } } class People { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public People(int age, String name){ this.age = age; this.name = name; } @Override public boolean equals(Object obj){ return obj instanceof People && age == ((People)obj).getAge() && name.equals(((People)obj).getName()); } @Override public int hashCode() { int hashCode = 17; hashCode = 31 * hashCode + this.age; hashCode = 31 * hashCode + (this.name == null ? 0 : this.name.hashCode()); return hashCode; } } |
DsExcel allows you to perform JSON I/O and PDF exporting for SpreadJS files containing cell padding and labels. You can also download the JSON file containing cell padding and labels from here.
In addition to this, DsExcel also provides CellPadding and Margin class, ILabelOptions interface, LabelAlignment and LabelVisibility enumerations to support cell padding and labels in DsExcel.
The following example code adds cell padding and labels in a DsExcel worksheet.
Java |
Copy Code |
---|---|
// Create a new workbook Workbook workbook = new Workbook(); // Get the sheet IWorksheet worksheet = workbook.getWorksheets().get(0); // Set row height worksheet.getRange("A:A").setRowHeight(40); // Set column width worksheet.getRange("A:A").setColumnWidth(25); // Set watermark worksheet.getRange("A1").setWatermark("JAVA"); // Set cell padding worksheet.getRange("A1").setCellPadding(new CellPadding(50, 0, 0, 0)); // Set label options worksheet.getRange("A1").getLabelOptions().setVisibility(LabelVisibility.visible); worksheet.getRange("A1").getLabelOptions().setForeColor(Color.GetGreen()); worksheet.getRange("A1").getLabelOptions().setMargin(new Margin(15, 0, 0, 0)); worksheet.getRange("A1").getLabelOptions().getFont().setSize(14); worksheet.getRange("A1").getLabelOptions().getFont().setName("Calibri"); worksheet.getRange("A1").getBorders().setLineStyle(BorderLineStyle.Thin); // Save to a pdf file workbook.save("CellPaddingAndLabels.pdf"); |
In MS Excel, when a number or date does not fit in the available cell width, it masks the cell value and displays "####" in the cell. To overcome this, DsExcel provides NumbersFitMode enumeration so that you can choose to either mask or show entire number or date value when cell is not wide enough to accommodate the entire value. The enumeration can be set using the setNumbersFitMode method and can have "Mask" or "Overflow" values. To avoid displaying "####", you can set the enumeration option to "Overflow" so that overflowing value occupies the space of blank neighboring cell. No overflow happens and only partial value is displayed in case the cell itself or the neighboring cell is a merged cell or has value in it.
NumbersFitMode = Mask | NumbersFitMode = Overflow |
---|---|
C# |
Copy Code |
---|---|
// Set numbersFitMode is overflow.
workbook.getBookView().setNumbersFitMode(NumbersFitMode.Overflow); |
This overflow behavior and direction vary according to the horizontal alignment and orientation of the cell values. The following table displays a value longer than the available width and its overflow behavior with different horizontal alignment and orientation.
Horizontal Alignment/Orientation | Overflow Behavior |
---|---|
General or right alignment | |
Left alignment | |
Center Alignment | |
Orientation greater than zero | |
Orientation less than zero |
DsExcel enables you to add a filter above the first row containing data using an overload of autoFilter method of IRange interface, comprising isFirstRowData boolean type parameter, so that you can filter the first row.
Refer to the following example code to add a filter to the first row containing data using isFirstRowData parameter of autoFilter method:
Java |
Copy Code |
---|---|
// Create a new workbook. Workbook workbook = new Workbook(); IWorksheet worksheet = workbook.getWorksheets().get(0); // Add data to the range. Object data = new Object[][]{ {"Luigi", "New York", new GregorianCalendar(1998, Calendar.APRIL, 8), "Blue", 67, 165}, {"Richard", "New York", new GregorianCalendar(1968, Calendar.JUNE, 8), "Blue", 67, 165}, {"Nia", "New York", new GregorianCalendar(1972, Calendar.JULY, 3), "Brown", 62, 134}, {"Jared", "New York", new GregorianCalendar(1964, Calendar.MARCH, 2), "Hazel", 72, 180}, {"Natalie", "Washington", new GregorianCalendar(1972, Calendar.AUGUST, 8), "Blue", 66, 163}, {"Damon", "Washington", new GregorianCalendar(1986, Calendar.FEBRUARY, 2), "Hazel", 76, 176}, {"Angela", "Washington", new GregorianCalendar(1993, Calendar.FEBRUARY, 15), "Brown", 68, 145} }; worksheet.getRange("A1:F7").setValue(data); // Set column width. worksheet.getRange("A:F").setColumnWidth(15); // Apply filter to first row. worksheet.getRange("A1:F7").autoFilter(true, 4, "<72"); // Create a file stream to export ssjson file. FileOutputStream outputStream = null; try { outputStream = new FileOutputStream("HeadersAsData.ssjson"); } catch (FileNotFoundException e) { e.printStackTrace(); } // Export the ssjson file. workbook.toJson(outputStream); // Close the stream. try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } |
DsExcel supports JSON I/O and PDF exporting of SpreadJS files containing background images. You can also download the JSON file containing background image from here.
DsExcel also provides getBackgroundPictures method in IWorksheet interface to add background pictures in DsExcel. For more information, refer Support Sheet Background Image.
The following example code sets background image in DsExcel worksheet.
Java |
Copy Code |
---|---|
// Create a new workbook Workbook workbook = new Workbook(); // Get the sheet IWorksheet worksheet = workbook.getWorksheets().get(0); // Load an image from a specific file in input stream InputStream stream = new FileInputStream("image.png"); // Add background picture IBackgroundPicture picture = worksheet.getBackgroundPictures().addPictureInPixel(stream, ImageType.PNG, 10, 10, 500, 370); // Set image layout picture.setBackgroundImageLayout(ImageLayout.Zoom); // Set options workbook.getActiveSheet().getPageSetup().setPrintGridlines(true); // Save to a pdf file workbook.save("BackgroundImage.pdf"); |
The following example code imports background image from JSON and exports to PDF document.
Java |
Copy Code |
---|---|
// Create a new workbook Workbook workbook = new Workbook(); // Load JSON file FileInputStream stream = new FileInputStream("BackgroundImage.json"); workbook.fromJson(stream); // Save file workbook.save("BackgroundImage.pdf"); |
Limitations
DsExcel supports JSON I/O and PDF exporting of SpreadJS files containing background color. You can also download the JSON file containing background color from here.
DsExcel also provides setBackColor and setGrayAreaBackColor methods in IWorkbookView interface to set background color in DsExcel.
The following code example sets background color for all the worksheets in DsExcel.
Java |
Copy Code |
---|---|
// Create a new workbook Workbook workbook = new Workbook(); // Get the sheet IWorksheet worksheet = workbook.getWorksheets().get(0); // Set background color workbook.getBookView().setBackColor(Color.GetLightSkyBlue()); workbook.getBookView().setGrayAreaBackColor(Color.GetGray()); worksheet.getRange("H20").setValue("The text"); // Set page options worksheet.getPageSetup().setPrintGridlines(true); worksheet.getPageSetup().setPrintHeadings(true); // Save to a pdf file workbook.save("BackgroundColor.pdf"); |
Limitation
In SpreadJS, background image always overrides the background color. Thus, the background image needs to be removed for the background color to take effect while exporting to PDF documents.
DsExcel allows you to set the count of rows and columns in a worksheet while performing JSON I/O. The setRowCount and setColumnCount methods of the IWorksheet interface can be used to achieve the same. You can also use the setIgnoreRangeOutOfRowColumnCount method of SerializationOptions class to choose whether to export the data outside the range of specified row and column count or not. The default value of this method is false which exports the data outside the range of specified row and column count to JSON.
Refer to the following example code which sets the row and column count in a worksheet and exports it to a JSON file.
Java |
Copy Code |
---|---|
//create a new workbook Workbook workbook = new Workbook(); IWorksheet worksheet = workbook.getWorksheets().get(0); worksheet.getRange("A1").setValue(1); worksheet.getRange("A11").setValue(2); // Modify the row count and column count of the worksheet. worksheet.setRowCount(10); worksheet.setColumnCount(10); SerializationOptions options = new SerializationOptions(); options.setIgnoreRangeOutOfRowColumnCount(true); // Save to a json file. // Open this json file with spreadjs, you will find that the row count is 10, and the column count is 10. try { workbook.toJson(new FileOutputStream("RowColumnCount.json"), options); } catch (FileNotFoundException e) { e.printStackTrace(); } |
Limitation
The row and column count setting is only supported for JSON I/O and cannot be exported to Excel or PDF file.
DsExcel allows you to render column width based on pixels instead of characters using setPixelBasedColumnWidth method of WorkbookOptions class when exporting an SSJSON file as a PDF or image.
Refer to the following example code to render column width based on pixels when exporting as a PDF or image:
Java |
Copy Code |
---|---|
// Initialize WorkbookOptions. WorkbookOptions workbookOptions = new WorkbookOptions(); // Enable pixel-based column width for the workbook. workbookOptions.setPixelBasedColumnWidth(true); var workbook = new Workbook(workbookOptions); // Open SSJSON file. workbook.open("Event budget.ssjson"); IWorksheet worksheet = workbook.getWorksheets().get(0); // Save to a PDF and PNG file. workbook.save("SavePDFWithPixelBasedColumnWidth.pdf"); worksheet.toImage("SavePDFWithPixelBasedColumnWidth.png"); |
DsExcel allows you to set various properties of Tab Strip like its position, width, display new tab button, editing of worksheet name etc. while performing JSON I/O. The IWorkbook interface provides methods like setTabNavigationVisible, setNewTabVisible, setAllowSheetReorder, setTabStripWidth, setTabStripPosition etc.
Refer to the following example code which sets the position of tab strip to left and other tab strip properties.
Java |
Copy Code |
---|---|
//create a new workbook Workbook workbook = new Workbook(); workbook.getWorksheets().add(); workbook.getBookView().setAllowSheetReorder(false); workbook.getBookView().setTabEditable(false); workbook.getBookView().setTabNavigationVisible(false); workbook.getBookView().setTabStripPosition(SpreadJSTabStripPosition.Left); workbook.getBookView().setTabStripWidth(150); workbook.getBookView().setNewTabVisible(false); try { workbook.toJson(new FileOutputStream("sheettabposition.json")); } catch (FileNotFoundException e1) { e1.printStackTrace(); } |
DsExcel supports setting the size of Check Box, Check Box List and Radio Box List Cells while performing JSON I/O. The setBoxSize and setAutoBoxSize methods are provided in the CheckBoxCellType, CheckBoxListCellType and RadioButtonListCellType classes. The setBoxSize method can be used to set the size of cell whereas the setAutoBoxSize method can be used to enable whether the box size should change with font size.
Refer to the following example code which sets the box size and setAutoBoxSize method to true for Check Box List cell.
Java |
Copy Code |
---|---|
//create a new workbook Workbook workbook = new Workbook(); IWorksheet worksheet = workbook.getWorksheets().get(0); CheckBoxListCellType celltype = new CheckBoxListCellType(); celltype.setTextAlign(CellTypeTextAlign.Right); celltype.setIsFlowLayout(false); celltype.setMaxColumnCount(2); celltype.setMaxRowCount(1); celltype.setHorizontalSpacing(20); celltype.setVerticalSpacing(5); celltype.setBoxSize(40); celltype.setAutoBoxSize(true); celltype.getItems().add(new SelectFieldItem("sample1", "1")); celltype.getItems().add(new SelectFieldItem("sample2", "2")); celltype.getItems().add(new SelectFieldItem("sample3", "3")); celltype.getItems().add(new SelectFieldItem("sample4", "4")); celltype.getItems().add(new SelectFieldItem("sample5", "5")); worksheet.getRange("A1:C3").setColumnWidth(25); worksheet.getRange("A1:C3").setCellType(celltype); worksheet.getRange("A1:C3").setValue(new Object[][]{ {new Object[]{"1", "3", "5"}} }); try { workbook.toJson(new FileOutputStream("checkboxlistsize.json")); } catch (FileNotFoundException e1) { e1.printStackTrace(); } |
DsExcel allows you to get the URL of a picture from a json file using getUrl method in the IPictureFormat interface. This URL is then converted to byte array and set to the picture by using setFill method of the IPictureFormat interface. This allows you to export the json file containing picture URL to an Excel or PDF file.
Refer to the following example code which gets the URL of a picture from JSON file and exports it to Excel and PDF formats.
Java |
Copy Code |
---|---|
private static byte[] GetPicFromUrl(String urlString) throws MalformedURLException, UnsupportedEncodingException { URL url = new URL(encode(urlString)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream inputStream = url.openStream()) { int n = 0; byte[] buffer = new byte[1024]; while (-1 != (n = inputStream.read(buffer))) { baos.write(buffer, 0, n); } } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); } private static String encode(String url) throws UnsupportedEncodingException { char[] charArray = url.toCharArray(); StringBuilder sb = new StringBuilder(); for (char c : charArray) { if (c >= 0 && c < 255) { sb.append(c); } else { sb.append(URLEncoder.encode(String.valueOf(c), "UTF-8")); } } return sb.toString(); } |