Personen mit Kommentaren benachrichtigen
In diesem Beispiel wird gezeigt, wie Sie einer Zelle Kommentare hinzufügen, einschließlich @mentioning einem Kollegen.
Beispielszenario
Der Teamleiter behält den Schichtplan bei. Sie weisen dem Schichtdatensatz eine Mitarbeiter-ID zu. Wenn der Teamleiter den Mitarbeiter benachrichtigen möchte, fügt er einen Kommentar hinzu, der den @mentions Mitarbeiter angibt. Dem Mitarbeiter wird eine benutzerdefinierte Nachricht aus dem Arbeitsblatt per E-Mail gesendet. Anschließend kann der Mitarbeiter die Arbeitsmappe anzeigen und nach Belieben auf den Kommentar reagieren.
Lösung
- Das Skript extrahiert Mitarbeiterinformationen aus dem Arbeitsblatt des Mitarbeiters.
- Das Skript fügt dann der entsprechenden Zelle im Schichtdatensatz einen Kommentar (einschließlich der entsprechenden Mitarbeiter-E-Mail) hinzu.
- Vorhandene Kommentare in der Zelle werden vor dem Hinzufügen des neuen Kommentars entfernt.
Setup: Excel-Beispieldatei
Diese Arbeitsmappe enthält die Daten, Objekte und Formatierungen, die vom Skript erwartet werden.
Beispielcode: Hinzufügen von Kommentaren
Fügen Sie der Beispielarbeitsmappe das folgende Skript hinzu, und probieren Sie das Beispiel selbst aus!
function main(workbook: ExcelScript.Workbook) {
// Get the list of employees.
const employees = workbook.getWorksheet('Employees').getUsedRange().getTexts();
// Get the schedule information from the schedule table.
const scheduleSheet = workbook.getWorksheet('Schedule');
const table = scheduleSheet.getTables()[0];
const range = table.getRangeBetweenHeaderAndTotal();
const scheduleData = range.getTexts();
// Find old comments, so we can delete them later.
const oldCommentAddresses = scheduleSheet.getComments().map(oldComment => oldComment.getLocation().getAddress());
// Look through the schedule for a matching employee.
for (let i = 0; i < scheduleData.length; i++) {
const employeeId = scheduleData[i][3];
// Compare the employee ID in the schedule against the employee information table.
const employeeInfo = employees.find(employeeRow => employeeRow[0] === employeeId);
if (employeeInfo) {
const adminNotes = scheduleData[i][4];
const commentCell = range.getCell(i, 5);
// Delete old comments, so we avoid conflicts.
if (oldCommentAddresses.find(oldCommentAddress => oldCommentAddress === commentCell.getAddress())) {
const comment = workbook.getCommentByCell(commentCell);
comment.delete();
}
// Add a comment using the admin notes as the text.
workbook.addComment(commentCell, {
mentions: [{
email: employeeInfo[1],
id: 0, // This ID maps this mention to the `id=0` text in the comment.
name: employeeInfo[2]
}],
richContent: `<at id=\"0\">${employeeInfo[2]}</at> ${adminNotes}`
}, ExcelScript.ContentType.mention);
} else {
console.log("No match for: " + employeeId);
}
}
}
Office Scripts