SpreadJS自定义单元格系列-HTML单元格

发布时间:2016/06/29 00:06 发布者:dexteryao

返回博客中心

单元格中单一颜色的问题略显枯燥,想要实现单元格中文字丰富的样式,只需要自定义HTML单元格。

HTML单元格

 

由于我们只是对单元格展示做调整所以我们直接继承GcSpread.Sheets.TextCellType,然后重写paint方法即可。

function HTMLCellType() {}
HTMLCellType.prototype = new GcSpread.Sheets.TextCellType;
HTMLCellType.prototype.paint = function (ctx, value, x, y, w, h, style, context) {
    var DOMURL = window.URL || window.webkitURL || window;
    var cell = context.sheet.getCell(context.row, context.col);
    var img = cell.tag();
    if (img) {
      try{
        ctx.save();
        ctx.rect(x, y, w, h);
        ctx.clip();
        ctx.drawImage(img, x + 2, y + 2)
        ctx.restore();
        cell.tag(null);
        return;
      }
      catch(err){
        GcSpread.Sheets.CustomCellType.prototype.paint.apply(this, [ctx, "#HTMLError", x, y, w, h, style, context])
        cell.tag(null);
        return;
      }
    }
    var svgPattern = '<svg xmlns="http://www.w3.org/2000/svg" width="{0}" height="{1}">' +
        '<foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="font:{2}">{3}</div></foreignObject></svg>';
    var data = svgPattern.replace("{0}", w).replace("{1}", h).replace("{2}", style.font).replace("{3}", value);
    var doc = document.implementation.createHTMLDocument("");
    doc.write(data);
    data = (new XMLSerializer()).serializeToString(doc.body.children[0]);
    img = new Image();
    img.src = 'data:image/svg+xml;base64,'+window.btoa(data);
    cell.tag(img);
    img.onload = function () {
        context.sheet.repaint(new GcSpread.Sheets.Rect(x, y, w, h));
    }
};

 

示例中我们使用svg将html元素保存为Image对象,然后保存在cell的tag中,spread重绘时展示出来。

RunJS在线演示地址http://runjs.cn/detail/imqwbthf 请在Edge或Chrome中查看

 


更多资源

SpreadJS中文学习指南:http://demo.grapecity.com.cn/SpreadJS/TutorialSample/#/samples

SpreadJS在线英文产品文档:http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#welcome.html

如果您对SpreadJS产品感兴趣,可以到官方网站下载试用:/developer/spreadjs

如果你有疑问,可以到GCDN论坛获得技术支持:http://gcdn.grapecity.com.cn


关于葡萄城

赋能开发者!葡萄城是专业的集开发工具、商业智能解决方案、低代码开发平台于一身的软件和服务提供商,为超过 75% 的全球财富 500 强企业提供服务。葡萄城专注控件软件领域30年,希望通过模块化的开发控件、灵活的低代码应用开发平台等一系列开发工具、解决方案和服务,帮助开发者快速响应复杂多变的业务需求,最大程度地发挥开发者的才智和潜能,让开发者的 IT 人生更从容更美好。

了解详情,请访问葡萄城官网