[]
        
(Showing Draft Content)

导入和导出JSON文件

GcExcel Java支持 SpreadJS 文件的JSON I/O。您还可以导入用SpreadJS Designer创建的ssjson文件,并在根据您的首选项修改后将其保存回去。

下面的示例代码加载一个ssjson文件,然后将其保存为xlsx格式。

// 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");

注意: 加载 SpreadJS JSON 文件时, 如果用户获取IBorder 接口的  getColorIndex 方法以设置索引颜色, 则仅当IBorder接口的 getColor 属性设置为任何rgb颜色时,它才会返回有效值;否则,它将返回-2作为无效标志。通常,索引颜色可以转换为rgb颜色,但反之亦然是不可能的。

GcExcel支持JSON I/O的以下特性。您可以使用fromJsontoJson方法来实现相同的功能,如上面的示例代码所示。

形状

GcExcel Java 允许您对包含形状的SpreadJS文件执行JSON I/O。您还可以下载包含shape的JSON文件。

shape.rar

条码

GcExcel支持包含条形码的SpreadJS文件的JSON I/O和PDF导出。但是,在导出为PDF时,支持部分扩展JS条形码属性。 有关不支持的属性的详细信息,请参阅 导出条形码


您还可以下载包含条形码的JSON文件。

barcode.zip

单元格按钮

GcExcel支持包含单元格按钮的SpreadJS文件用于JSON I/O、HTML、图像和PDF导出。 您还可以下载包含单元格按钮的JSON文件。

CellButtons.rar


单元格下拉菜单

GcExcel支持包含计算器、颜色选择器、时间选择器等单元格下拉列表的SpreadJS文件的JSON I/O。 您还可以下载包含单元格下拉列表的JSON文件。

CellDropdowns.rar

表单控件

GcExcel 支持读写包含表单控件(如按钮、下拉框、复选框等)的 SpreadJS 文件的 JSON 格式。这意味着您可以将表单控件导入导出到 ssjson 文件。您还可以下载包含表单控件的 JSON 文件。

FormControls.rar

验证样式

验证样式可用于突出显示工作表中的无效数据。GcExcel支持包含验证样式的SpreadJS文件的JSON I/O、图像和PDF导出。 您还可以下载包含验证样式的JSON文件。

ValidationStyle.rar

文本省略

当单元格中的文本长于列宽时,SpreadJS允许您显示省略号,而不是在另一个单元格中溢出文本。GcExcel中的JSON I/O和PDF导出支持包含文本省略号的SpreadJS文件。 您还可以下载包含文本省略号的JSON文件。

TextEllipsis.rar


局限性

SpreadJS允许用文本省略号组成不同类型的文本对齐,但GcExcel不允许。因此,文本省略号仅显示在导出的PDF中文本的末尾。

区域模板

在SpreadJS中,您可以创建一个区域单元格类型,该类型可用于将工作表中的单元格区域指定为模板。您只需更改模板即可修改结果数据的显示模式和外观。 GcExcel支持包含 区域模板的SpreadJS文件的JSON I/O和PDF导出。

你也可以下载包含range模板的JSON文件。

RangeTemplate.rar

格式化字符串

SpreadJS支持 格式化字符串 特性,允许单元格将公式和文本作为文本值模板的一部分。GcExcel支持包含格式字符串的SpreadJS文件的JSON I/O。

你也可以下载包含格式化字符串的JSON文件。

FormatString.rar

JSON 选项

在SpreadJS中,从JSON对象导入或导出自定义数据时,可以设置多个序列化或反序列化选项。GcExcel还支持工作簿和工作表JSON I/O以及GcExcel API中的一些选项。下表说明了SpreadJS和GcExcel中支持的选项。


SpreadJS (toJSON and fromJSON)

GcExcel (toJSON and fromJSON)

Serialization

ignoreStyle

ignoreFormula

rowHeadersAsFrozenColumns

columnHeadersAsFrozenRows

ignoreStyle

ignoreFormula

getIgnoreColumnRowInfoOutOfUsedRange

setIgnoreColumnRowInfoOutOfUsedRange

getIgnoreRangeOutOfRowColumnCount 

setIgnoreRangeOutOfRowColumnCount 

setExportSharedFormula

Deserialization

ignoreStyle

ignoreFormula

frozenColumnsAsRowHeaders

frozenRowsAsColumnHeaders

doNotRecalculateAfterLoad

ignoreStyle

ignoreFormula

doNotRecalculateAfterLoad

GcExcel在API中提供了带有上述支持属性的序列化选项反序列化选项类。

下面的示例代码使用GcExcel中的选项将工作簿序列化为JSON。

// 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");

下面的示例代码使用GcExcel中的选项从JSON反序列化工作簿。

// 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");

您可以通过选择是否保留超出使用范围的行和列的样式和大小来控制导出的 JSON 文件的大小。在SerializationOptions类中提供了setIgnoreColumnRowInfoOutOfUsedRange方法:

  • 当设置为 true(默认值)时,不导出超出使用范围的行和列的样式和大小,因此文件大小更小。

  • 设置为 false 时,导出超出使用范围的行和列的样式和大小,因此文件大小更大。

以下示例代码显示了设置上述方法如何影响 JSON 文件的大小。

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();
}

您还可以使用 SerializationOptions 类中的 setExportSharedFormula 方法来控制在导出到 JSON 文件时是否将公式导出为共享公式。当该选项设置为 true 时(默认值),您可以将公式导出为共享公式。但是,如果将该选项设置为 false,则公式将被导出为个别公式。

在 GcExcel v6.0.1 及更高版本中,公式会作为共享公式导出到 JSON 文件(或 SSJSON 文件)。然而,由于共享公式与 GcExcel v5 及以下版本以及 SpreadJS v15 及以下版本不兼容,因此您可以使用这个选项来实现向后兼容,并在导出的 JSON 文件中跳过共享公式。

以下示例代码将公式导出为共享公式:

 // 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();
}     

注意: SpreadJS支持多级行或列标题,但GcExcel不支持。但是,您仍然可以通过以下步骤在GcExcel中保留标题信息:

  1. 使用SpreadJS将带有“rowHeadersAsFrozenColumns或columnHeadersAsFrozenRows”选项的JSON导出为true,以将多标题转换为冻结区域,并使用GcExcel加载JSON文件。

  2. 在GcExcel中操作冻结区域。

  3. 使用GcExcel导出JSON文件,并使用SpreadJS加载JSON文件,其中“frozenColumnSarrowHeaders或frozenRowsAsColumnHeaders”选项为true,以将冻结区域转换为标头。

复选框或单选按钮列表单元格类型

GcExcel支持JSON I/O和PDF导出包含复选框列表和单选按钮列表单元格类型的SpreadJS文件。 您还可以下载包含单选按钮列表和复选框列表单元格类型的JSON文件。

CheckBoxList_RadioButtonList.rar

GcExcel还在其API中提供RadioButtonListCellTypeCheckBoxListCellType类来添加这些单元格类型。

下面的示例代码为GcExcel中的单元格创建复选框列表单元格类型。

//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");    

以下示例代码创建复选框列表单元格类型,并将选项的值设置为自定义对象。

//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;
}
}

T以下示例代码为 GcExcel 中的单元格创建单选列表单元格类型。

//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");

以下示例代码创建单选按钮单元格类型,并将选项的值设置为自定义对象。

//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;
}
}

单元格内边距(Padding)和标签(Labels)

GcExcel 允许您为包含单元格内边距和标签的 SpreadJS 文件执行 JSON I/O 和 PDF 导出。你可以下载一个包含内边距和标签的SSJSON文件。

CellPaddingandLabel.rar

除此之外, GcExcel还提供了CellPaddingMargin 类,ILabelOptions 接口, LabelAlignmentLabelVisibility 枚举,来支持单元格内边距(padding)和标签(labels)。

以下示例代码在 GcExcel 工作表中添加单元内边距和标签。

// 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("GcExcel 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");

数字适配模式

在MS Excel中,当数字或日期不符合可用单元格宽度时,它会屏蔽单元格值,并在单元格中显示“####”。为了克服这个问题,GcExcel提供了NumbersFitMode枚举,这样当单元格宽度不够容纳整个数值时,您可以选择屏蔽或显示整个数值或日期值。枚举可以使用setNumbersFitMode方法设置,并且可以有"Mask"或"Overflow"两个值。为了避免显示“#####”,可以将枚举选项设置为"Overflow",使溢出值占据相邻空白单元格的空间。如果单元格本身或相邻单元格是合并单元格或其中包含值,则不会发生溢出,只显示部分值。

NumbersFitMode = Mask

NumbersFitMode = Overflow



// Set numbersFitMode is overflow.
workbook.getBookView().setNumbersFitMode(NumbersFitMode.Overflow);

这种溢出行为和方向根据单元格值的水平对齐和方向而变化。以下表格显示了一个长度超过可用宽度的值,以及不同水平对齐和方向下的溢出行为。

Horizontal Alignment/Orientation

Overflow Behavior

General or right alignment


Left alignment


Center Alignment


Orientation greater than zero


Orientation less than zero


**注意:**由于MS Excel不支持NumbersFitMode,因此NumbersFitMode.Overflow选项在将工作表导出到MS Excel时无效。

背景图片

GcExcel支持JSON I/O和PDF导出包含背景图像的SpreadJS文件。您还可以下载包含背景图像的JSON文件。

BackgroundImage.rar

GcExcel还在IWorksheet接口提供getBackgroundPictures 方法,在GcExcel中添加背景图片。想要了解更多信息,请参考 支持表单背景图片

下面的示例代码在GcExcel工作表中设置背景图像。

// 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("grapecity.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");

以下示例代码从 JSON 导入背景图像并导出到 PDF 文档。

// 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");

限制

  • 从JSON导入时,背景图像放置在每个工作表的(左:0,上:0)位置。

  • 导出为PDF后,PDF文档的所有页面都将具有与从ssjson导入的相同的背景图像

背景颜色

GcExcel支持JSON I/O和PDF导出包含背景色的SpreadJS文件。您还可以下载包含背景色的JSON文件。

BackgroundColor.rar

GcExcel在IWorkbookView界面中还提供了设置GcExcel背景色的方法。

下面的代码示例为GcExcel中的所有工作表设置背景色。

// 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");

限制

在SpreadJS中,背景图像总是覆盖背景颜色。因此,在导出为PDF文档时,需要删除背景图像才能使背景色生效。

行数和列数

GcExcel 允许您在使用 JSON I/O 时设置工作表中的行数和列数。IWorksheet接口中的setRowCountsetColumnCount 方法可以实现同样效果。你也可以使用SerializationOptions类的setIgnoreRangeOutOfRowColumnCount方法选择是否导出指定行列数以外的数据。此方法的默认值是 false,将指定行和列数范围之外的数据导出到JSON。

请参阅以下示例代码,该代码在工作表中设置行数和列数并将其导出到 JSON 文件。

//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();
}

局限性

行和列计数设置仅支持 JSON I/O,不能导出到 Excel 或 PDF 文件。

设置标签条(Tab Strip)

GcExcel 允许您在执行 JSON I/O 时设置 Tab Strip 的各种属性,例如其位置、宽度、显示新标签按钮、编辑工作表名称等。IWorkbook接口提供了以下等方法:setTabNavigationVisible, setNewTabVisible, setAllowSheetReorder, setTabStripWidth, setTabStripPosition

参考下面的示例代码,将标签条的位置设置为左侧和其他标签条属性。

//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();
}

设置复选框、复选框列表和单选框列表单元格的大小

GcExcel 支持在执行 JSON I/O 时设置 Check Box、Check Box List 和 Radio Box List Cells 的大小。CheckBoxCellType, CheckBoxListCellTypeRadioButtonListCellType 都提供了 setBoxSizesetAutoBoxSize 方法。setBoxSize 方法可用于设置单元格的大小,而 setAutoBoxSize 方法可用于启用框大小是否应随字体大小而变化。

请参阅以下示例代码,该代码将复选框列表单元格的框大小和 setAutoBoxSize 方法设置为 true。

//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();
}

获取图片URL

GcExcel 允许你从一个 json 文件中获取图片的 URL,使用IPictureFormat接口中的getUrl 方法。然后将此 URL 转换为字节数组并使用 IPictureFormat 接口的 setFill 方法设置为图片。这允许您将包含图片 URL 的 json 文件导出到 Excel 或 PDF 文件。

请参考以下示例代码,它从 JSON 文件中获取图片的 URL 并将其导出为 Excel 和 PDF 格式。

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();
}