本帖最后由 AlexZ 于 2023-5-12 15:16 编辑
注:使用工作簿拼接时,可能会受到工作簿级别命名样式、跨sheet公式等等因素的影响,出现未知的错误。
官方角度不建议这样使用,但考虑到实际需求,您可以参考上述文章实际测试下。
如后续有出现异常问题可以另开新帖咨询。
需求:
1、将两个工作簿(Workbook)合并到一个工作簿中
2、将一个工作簿中的两个工作表sheet合并为1个
步骤:
合并工作簿代码:
- for(let i=0; i<datas.length; i++){
- var temp = new GC.Spread.Sheets.Workbook(document.getElementById("ss1"));
- temp.fromJSON(datas[i]);
- // 重命名样式表
- temp.getNamedStyles().forEach(function (namedStyle) {
- namedStyle.name = "sc" + i + "_" + namedStyle.name;
- spread.addNamedStyle(namedStyle);
- });
- var sheetCount = temp.getSheetCount();
- for(let j=0; j<sheetCount; j++){
- let sheet = temp.getSheet(j);
- let sheetJSON = JSON.stringify(sheet.toJSON());
- sheetJSON = sheetJSON.replace(/"style":"/g, '"style":"sc' + i + "_");
- // 如果存在parentName,则添加以下代码:
- // sheetJSON = sheetJSON.replace(/"parentName":"/g, '"parentName":"sc' + i + "_");
- spread.suspendPaint();
- var newSheet = new GC.Spread.Sheets.Worksheet("sheet" + i + "_");
- newSheet.fromJSON(JSON.parse(sheetJSON));
- newSheet.name(newSheet.name()+i+"_"+j);
- spread.addSheet(spread.getSheetCount(), newSheet);
- spread.resumePaint();
-
- }
-
- }
- spread.removeSheet(0);
复制代码
合并sheet代码:
- spread.suspendPaint();
- //新增一个sheet,用来放拼接后的表单
- var newSheeet = new GC.Spread.Sheets.Worksheet("new sheet");
- spread.addSheet(spread.getSheetCount(), newSheeet);
- var workbook = spread;
- workbook.options.allowExtendPasteRange = true;
- //sheet1、sheet2行列数
- var sheet1 = workbook.getSheet(0);
- var rc1 = sheet1.getRowCount();
- var cc1 = sheet1.getColumnCount();
- var sheet2 = workbook.getSheet(1);
- var rc2 = sheet2.getRowCount();
- var cc2 = sheet2.getColumnCount();
- var sheet3 = workbook.getSheet(2);
- var sheetName = sheet3.name();
- //全选复制sheet1,粘贴至sheet3
- var fromRange1 = [new GC.Spread.Sheets.Range(-1, -1, -1, -1)];
- var toRange1 = [new GC.Spread.Sheets.Range(0, 0, rc1, cc1)];
- workbook.commandManager().execute(
- {
- cmd: "clipboardPaste",
- sheetName: sheetName,
- fromSheet: sheet1,
- fromRanges: fromRange1,
- pastedRanges: toRange1,
- isCutting: false,
- clipboardText: "",
- pasteOption: GC.Spread.Sheets.ClipboardPasteOptions.all
- }
- );
- sheet3.addColumns(cc1-1, cc2);
- //全选复制sheet2,粘贴至sheet3
- var fromRange2 = [new GC.Spread.Sheets.Range(-1, -1, -1, -1)];
- debugger;
- var toRange2 = [new GC.Spread.Sheets.Range(0, cc1+1, rc2, cc2)];
- workbook.commandManager().execute(
- {
- cmd: "clipboardPaste",
- sheetName: sheetName,
- fromSheet: sheet2,
- fromRanges: fromRange2,
- pastedRanges: toRange2,
- isCutting: false,
- clipboardText: "",
- pasteOption: GC.Spread.Sheets.ClipboardPasteOptions.all
- }
- );
- //获取sheet1图片,添加在sheet3内
- var pic = sheet1.pictures.all()[0];
- sheet3.pictures.add('f2', pic.src(), pic.x(), pic.y(), pic.width(), pic.height());
- //删除sheet1、sheet2
- workbook.removeSheet(1);
- workbook.removeSheet(0);
- //取消选中状态
- sheet3.clearSelection();
- spread.resumePaint();
复制代码
最终效果如下图所示:
完整代码见附件。
|
|