SpreadJS+GCExcel实现数据绑定
本帖最后由 Ellia.Duan 于 2022-9-28 09:43 编辑SpreadJS作为纯前端类Excel的表格控件,可以很好的设计模板。GCExcel作为一个高性能,低内存的电子表格组件,它提供给开发人员一套丰富并且强大的API集合,用以生成,操作,转换,分享与微软Excel兼容的电子表格。SpreadJS + GCExcel 结合使用,将产生1+1>2的效果。那么,如果在Spread中进行模板设计,在GCExcel中进行数据绑定,该怎么做呢?一起来看看吧首先在线表格编辑器中设计模板与字段,如下图所示:设计模板与字段后,添加工具栏按钮“数据绑定”。var config = JSON.parse(JSON.stringify(GC.Spread.Sheets.Designer.DefaultConfig))
config.commandMap = {
BindData: {
title: "BindData data to server",
text: "数据绑定",
iconClass: "ribbon-button-welcome",
bigButton: "true",
commandName: "BindData",
execute: async (context, propertyName, fontItalicChecked) => {}
config.ribbon.buttonGroups = {
thumbnailClass: "save",
commandGroup: {
children: [
{
direction: "vertical",
commands: ["BindData"],
}
],
},
};
designer.setConfig(config)
此按钮的作用在于将当前模板转换为json数据,传送给后端。这里传送给后端的json数据由两部分组成,一部分由spread.toJSON()获取,一部分是模板绑定的字段schema由designer.getData()获取。具体的execute代码如下:execute: async (context, propertyName, fontItalicChecked) => {
let spread = context.Spread;
let formData = new FormData();
let json = spread.toJSON({
includeBindingSource: true
})
var designerBindingPathSchema = designer.getData("treeNodeFromJson") || designer.getData("updatedTreeNode") || designer.getData("oldTreeNodeFromJson");
json.schema = designerBindingPathSchema
formData.append('json',JSON.stringify(json))
$.ajax({
type: "post",
url: "http://localhost:8080/excel",
data: formData,
processData: false,
contentType: false,
success: function (data) {
spread.fromJSON(JSON.parse(data))
},
error: function () {
alert("请求失败");
}
});
},
前端发出请求后,后端接收请求。后端使用SPringMVC框架接收‘/excel’post请求@PostMapping (value = "/excel")
@CrossOrigin
public String greeting(@RequestParam(name="json") String json, Model model) {
}
接收到json数据后,GCExcel使用fromJson()方法进行模板场景恢复。之后使用setDataSource()进行数据绑定。 model.addAttribute("json", json);
Workbook workbook = new Workbook();
workbook.fromJson(json);
StationInfo stationInfo = new StationInfo();
stationInfo.name = "九三实验站";
stationInfo.date = String.valueOf(new Date());
stationInfo.rainFalls = new ArrayList<RainFall>();
RainFall rainFall = new RainFall();
rainFall.time = "03:12";
rainFall.precipitation = "21.23";
rainFall.rain = "0.23";
rainFall.record_person = "李四";
rainFall.remark = "";
stationInfo.rainFalls.add(rainFall);
IWorksheet worksheet = workbook.getWorksheets().get(0);
worksheet.setDataSource(stationInfo);此时注意stationInfo类中name字段、date字段、rainFallls字段同模板绑定中的字段一致。如下图所示:最后数据绑定成功后,GCExcel还可以实现导出pdf功能,导出excel功能workbook.save("json/test.pdf");
workbook.save("json/test.xlsx");如果前端想获取绑定后的数据,可以通过 toJson()方法获取GCExcel导出的json数据,返回给前端。String jsonWithOption = workbook.toJson();
return jsonWithOption;前端接收后端返回的json数据,通过fromJSON()来进行绑定后的数据展示。具体看ajax中success方法 $.ajax({
type: "post",
url: "http://localhost:8080/excel",
data: formData,
processData: false,//必须
contentType: false,//必须
success: function (data) {
spread.fromJSON(data)
},
error: function () {
alert("请求失败");
}
});至此,SpreadJS+GCExcel前后端交互一起完成了数据绑定。
具体代码见附件
页:
[1]