单元格操作
设置单元格值
设置值
要通过 API 为单元格设置值,请使用 setValue() 方法。向该方法传入以下参数:
cells- (string) 单元格或单元格区域的 idvalue- (string/number/array) 要为单元格设置的值
// setting value for one cell
spreadsheet.setValue("A1",5);
// setting the same value for a range of cells
spreadsheet.setValue("A1:D1",5);
// setting the same value for different cells
spreadsheet.setValue("B6,A1:D1",5);
// setting values from an array for cells in a range alternately
spreadsheet.setValue("A1:D1",[1,2,3]);
备注
请注意,该方法为指定的单元格设置相同(重复)的值。如果要向电子表格单元格中添加不同的值,请使用 parse() 方法。
获取值
您也可以通过将所需单元格或单元格区域的 id 传入 getValue() 方法来返回单元格中的值。
该方法以字符串、 数字或数组的形式返回值:
// returning the value of one cell
var cellValue = spreadsheet.getValue("A2"); // "Ecuador"
// returning the values of the range of cells
var rangeValues = spreadsheet.getValue("A1:A3"); // -> ["Country","Ecuador","Belarus"]
// returning the values of different cells
var values = spreadsheet.getValue("A1,B1,C1:C3");
//-> ["Country", "Product", "Price", 6.68, 3.75]
验证单元格
从 v4.3 开始,您可以通过添加下拉选项列表对单元格应用数据验证。为此,请使用 setValidation() 方法:
spreadsheet.setValidation("B10:B15", ["Apple", "Mango", "Avocado"]);
下拉列表限制了用户的选择范围。当用户在单元格中输入意外值时,将显示 无效值 消息。
信息
setValidation() 方法也可以从指定单元格中移除验证。查看详情。
在单元格中插入超链接
要在单元格中插入超链接,请使用 insertLink() 方法。该方法还可以添加与超链接一起显示的文本:
// insert a link in "A2" cell
spreadsheet.insertLink("A2", {
text:"DHX Spreadsheet", href: "https://dhtmlx.com/docs/products/dhtmlxSpreadsheet/"
});
如果需要从单元格中删除链接,只需向该方法传入单元格 ID:
// remove a link from "A2" cell
spreadsheet.insertLink("A2");
设置单元格样式
设置样式
您可以使用 setStyle() 方法为单元格或单元格区域应用样式。该方法接受两个参数:
cells- (string) 单元格或单元格区域的 idstyles- (object/array) 要应用于单元格的样式
// setting style for one cell
spreadsheet.setStyle("A1", {background: "red"});
// setting the same style for a range of cells
spreadsheet.setStyle("A1:D1", {color: "blue"});
// setting the same style for different cells
spreadsheet.setStyle("B6,A1:D1", {color: "blue"});
// setting styles from an array for cells in a range alternately
spreadsheet.setStyle("A1:D1", [{color: "blue"}, {color: "red"}]);
备注
该方法为指定的单元格设置相同的样式。如果要对电子表格单元格应用不同的样式,请使用 parse() 方法。
获取样式
要获取应用于单元格的样式,请使用 getStyle() 方法。向其传入单元格或单元格区域的 id:
// getting style of one cell
var style = spreadsheet.getStyle("A1");
// -> {background: "#8DE9E1", color: "#03A9F4"}
// getting styles of a range of cells
var rangeStyles = spreadsheet.getStyle("A1:D1"); // -> see details
// getting styles of different cells
var values = spreadsheet.getStyle("A1,B1,C1:C3");
对于多个单元格,该方法返回一个包含各单元格样式的对象数组:
[
{background: "red", border: "solid 1px yellow", color: "blue"},
{background: "red", border: "solid 1px yellow", color: "blue"},
{background: "#C8FAF6", border: "solid 1px yellow", color: "#81C784"},
{background: "#9575CD", border: "solid 1px yellow", color: "#079D8F"}
]