Skip to content

7.8 脚本案例

7.8.1 字符拼接

引用其它js文件,调用方法concat,返回’hello,world’字符串。

js
import {concat} from 'scripts/module.js'//必须是全路径
export function helloworld() {
	return concat('hello','world');
}

结果:hello & world

7.8.2 查询数据表记录

从人员表中查询姓名中包含张或李且年龄大于20岁的前3位员工,按照年龄从低到高排序

js
export function queryList() {
    return informat.table.queryList('scriptTableA',{
		pageIndex:1,
		pageSize:3,
        filter:{
    		opt:'and',
    		conditionList:[
          	    {fieldId:'age',opt:'gt',value:'20'},
        	],
            children:[
        		{
        			opt:'or',
        			conditionList:[
	          			{fieldId:'name',opt:'startswith',value:'张'},
	          			{fieldId:'name',opt:'startswith',value:'李'}
        			]
        		}	
            ]
        },
		orderByList:[{ field: 'age', type: 'asc' }]
    })
}

返回结果:

json
[
    {
        "sex": "male",
        "updateUser": "skydu",
        "updateTime": 1701156631331,
        "createTime": 1701156631331,
        "grade": 5,
        "name": "李十二",
        "createUser": "skydu",
        "id": "bqlqzxvg248l6",
        "age": 23,
        "seq": 15
    },
    {
        "sex": "female",
        "updateUser": "skydu",
        "updateTime": 1700796135362,
        "createTime": 1700796135362,
        "grade": 5,
        "name": "李四",
        "createUser": "skydu",
        "id": "yhg8b23ej2gt6",
        "age": 26,
        "seq": 2
    },
    {
        "sex": "female",
        "updateUser": "skydu",
        "updateTime": 1701156638725,
        "createTime": 1701156615249,
        "grade": 3,
        "name": "张十一",
        "createUser": "skydu",
        "id": "in0h1mj8sl5jl",
        "age": 29,
        "seq": 14
    }
]

7.8.3 克隆附件字段

将A表的附件克隆到B表的附件字段中

js
/**克隆字段附件 */
export function cloneAttachment() {
    var record=informat.table.queryById('scriptTableA','bbafxnx0dgzsn');
	console.log('record.attachment',record.attachment);
	if(record.attachment==null){
		return null;
	}
	var targetAttachments=[];
	record.attachment.forEach(att=>{//多选
		var targetAttachment=informat.table.cloneAttachment('scriptTableA','attachment','scriptTableB','attachment',att);
		targetAttachments.push(targetAttachment);
	});
    console.log('targetAttachments',targetAttachments);
	informat.table.update('scriptTableB',{
		id:'rpev2ztqnbu8o',
		attachment:targetAttachments
	});
	return targetAttachments;
}

结果: 未触发脚本前: before 触发脚本后: after

7.8.4 将数据写入到Excel

将一个列表数据写入到Excel文件中

js
export function dataListToExcelFile(dataList = [], headers = {}, fileName) {
  const workbook=informat.excel.openNewFile(fileName);
  const sheet = workbook.createSheet("sheet1");

  // 构建表头
  const style = workbook.createCellStyle();
  const font = workbook.createFont();
  font.setBold(true);
  font.setItalic(true);
  font.setFontHeightInPoints(14);
  style.setFont(font);
  style.setFillBackgroundColor("#fafafa");//设置灰色背景
  style.setAlignment("CENTER");//水平居中
  style.setVerticalAlignment("CENTER");//垂直居中
  style.setFillPattern("SOLID_FOREGROUND");

  const headerIndexMap = {}
  const row = sheet.createRow(0);
  Object.keys(headers).forEach((key, index) => {
    headerIndexMap[key] = index;
    const cell = row.createCellWithValue(index, headers[key]);
    cell.setStyle(style);
  });

  // 构建数据
  const rowFont = workbook.createFont();
  rowFont.setBold(false);
  rowFont.setItalic(false);
  rowFont.setFontHeightInPoints(12);
  const dataStyle = workbook.createCellStyle();
  dataStyle.setFont(rowFont);
  dataStyle.setAlignment("CENTER");//水平居中
  dataStyle.setVerticalAlignment("CENTER");//垂直居中
  dataStyle.setFillPattern("SOLID_FOREGROUND");

  dataList.forEach((item, rowIndex) => {
    console.log('dataList', rowIndex);
    const row = sheet.createRow(rowIndex + 1);
    Object.keys(item).forEach((key) => {
      const index = headerIndexMap[key];
      if (typeof index === 'number') {
        console.log('createCellWithValue', key, item[key]);
        const cell = row.createCellWithValue(index, item[key]);
        cell.setStyle(dataStyle);
      }
    });
  });

  workbook.write();//写入文件
}

结果: 会成一个带有样式和数据的excel表格 export_excel

7.8.5 根据模版生成Word文件

通过模板生成Word文件,讲述如何渲染文本、图片、列表、表格行数据、表格列数据等场景

  1. 首先,准备一个word模版上传到服务器本地 wordTemplate
  2. 编写脚本填充模版
js
export function createWithTemplate() {
  const list = [
    {id:1,name:'张三'},
    {id:2,name:'李四'},
    {id:3,name:'王五'}
  ];
  const data={
    text:'文本数据',
    list,
    "-tableRowList": list,
    "|tableColList": list,
    pic:informat.word.createPicture({
      path:'logo.png'
    })
  }
  informat.word.createWithTemplate('template.docx','out.docx',data);
}

结果:
word

7.8.6 读取mpp文件

读取’脚本资源’模块里的MPP文件

js
const websitePath = 'mpp/软件开发.mpp';
const localPath = 'mpp/软件开发.mpp';
informat.website.download('scriptResource', websitePath, localPath);
let projectFile=informat.mpp.read(localPath);
var resourceAssignments=projectFile.getResourceAssignments();
var taskList=[];
resourceAssignments.list().forEach(as=>{
	  if (as.getTask() == null || as.getResource() == null) {
	      return;
	  }
	  var taskId = as.getTask().getID();
	  var resourceName=as.getResource().getName();
	  console.log('taskId:'+taskId+',resourceName:'+resourceName);
});
var tableContainer=projectFile.getTables();
if(tableContainer!=null&&tableContainer.size()>0) {
	    var columns = tableContainer.list().get(0).getColumns();
	    columns.forEach(c=>{
	    console.log('column:'+c.getTitle());
	    });
}
var tasks=projectFile.getTasks();
tasks.list().forEach(task=>{
	  console.log('taskId:'+task.getID()+',taskName:'+task.getName());
		taskList.push({
			id:task.getID(),
			uniqueID:task.getUniqueID(),
			name:task.getName(),
			wbs:task.getWBS(),
			start:task.getStart(),
			finish:task.getFinish(),
			duration:task.getDuration(),
			resourceNames:task.getResourceNames(),
			predecessors:task.getPredecessors()
		});
});

结果:

json
[
    {
        "duration":{
            "duration":95.75,
            "timeUnit":"d"
        },
        "predecessors":[

        ],
        "name":"软件开发",
        "start":1167609600000,
        "wbs":"0",
        "finish":1179126000000,
        "id":0,
        "uniqueID":0
    },
    {
        "duration":{
            "duration":3.5,
            "timeUnit":"d"
        },
        "predecessors":[

        ],
        "name":"项目范围规划",
        "start":1167609600000,
        "wbs":"1",
        "finish":1167883200000,
        "id":1,
        "uniqueID":1
    }
    ...
]

7.8.7 写入mpp文件

数据写入Mpp文件,并生成xml文件提供下载

js
var file = informat.mpp.createProjectFile();
var pmResource=file.addResource();
pmResource.setName("项目经理");
var devResource=file.addResource();
devResource.setName("开发人员");
var customFieldContainer = file.getCustomFields();
var field = customFieldContainer.getOrCreate('TEXT1');
field.setAlias("MyCustomField");
var task1 = file.addTask();
task1.setName("root");
task1.setTaskMode('MANUALLY_SCHEDULED');
task1.setStart(new Date());
task1.setFinish(new Date(2024,3,1));
task1.setText(1,'测试1')
task1.addResourceAssignment(pmResource);
task1.addResourceAssignment(devResource);
//
var task12 = task1.addTask();
task12.setName("任务A");
task12.setTaskMode('AUTO_SCHEDULED');
task12.setStart(new Date());
task12.setFinish(new Date(2024,2,1));
task12.setText(1, "text1");
task12.addResourceAssignment(devResource);
//
task1.addPredecessor(task12, null, null);
task12.addPredecessor(task1, null, null);
//
var task2 = file.addTask();
task2.setName("任务B");
task2.setTaskMode('MANUALLY_SCHEDULED');
task2.setStart(new Date(2024,4,1));
task2.setFinish(new Date(2024,5,1));
//
var config={
    microsoftProjectCompatibleOutput:false,
    splitTimephasedAsDays:true,
	writeTimephasedData:false,
    saveVersion:"Project2016"
}
informat.mpp.write(file, 'output.xml', config);

结果: mpp