To create a combo box cell, follow this example:
You can use the editorValueType method to get and set the value that is written to the underlying data model. The editor value type is an EditorValueType enumeration.
text: Writes to the model the text value of the selected item.
index: Writes to the model the index of the selected item.
value: Writes to the model the corresponding data value of the selected item.
The different editorValueType settings create different types of editor values. The combo box's value depends on items for the drop-down list in the combo box. You can use the items method to get and set the items. For example:
You can also use the dataBinding method to bind the combo box to a data source. The data source will replace the items in the combo box in runtime. For example:
Use the editable method to set whether the user can type in the combo box editor. The default value is false; only selection is allowed. For example:
You can use the itemHeight method to set the height of each item in the drop-down list. For example:
Use the allowFloat method to set whether to allow the drop-down list to float outside the Spread.
<template>
<div class="sample-tutorial">
<gc-spread-sheets class="sample-spreadsheets" @workbookInitialized="initSpread">
<gc-worksheet></gc-worksheet>
</gc-spread-sheets>
<div class="options-container">
<label>Select one of the combo box cells in Spread and edit its options with these text boxes.</label>
<div class="option-row">
<label>Editor Value Type:</label>
<select id="editorValueType" v-model="editorValueType">
<option v-for="(key, index) in editorValueTypeList" :value="index" :key="key">{{ key.charAt(0).toUpperCase() +
key.slice(1) }}</option>
</select>
</div>
<div class="option-row">
<label>Binding Type:</label>
<select id="binding-type" v-model="bindingType">
<option v-for="(key, index) in bindingTypeList" :value="index" :key="key">{{ key }}</option>
</select>
</div>
<div id="static-items" v-if="bindingType == 0">
<div class="option-row">
<label for="itemsText">Items Text:</label>
<input id="itemsText" type="text" v-model="itemsText" />
</div>
<div class="option-row">
<label for="itemsValue">Items Value:</label>
<input id="itemsValue" type="text" v-model="itemsValue" />
</div>
</div>
<div id="data-binding-items" v-if="bindingType == 1">
<div class="option-row">
<label>Data Source Type:</label>
<select id="selComboDataSourceType" v-model="dataSourceType">
<option v-for="(key, index) in dataSourceTypeList" :value="index" :key="key">{{ key }}</option>
</select>
</div>
<div v-if="dataSourceType == 0">
<div class="option-row">
<label>Data Source:</label>
<select id="selComboDataSource" v-model="tableName" @change="tableNameChanged">
<option v-for="(key) in tableNameList" :value="key">{{ key }}</option>
</select>
</div>
<div class="option-row">
<label>Binding Text:</label>
<select id="selComboText" v-model="textColumn">
<option v-for="(key) in columnNameList" :value="key">{{ key }}</option>
</select>
</div>
<div class="option-row">
<label>Binding Value:</label>
<select id="selComboValue" v-model="valueColumn">
<option v-for="(key) in columnNameList" :value="key">{{ key }}</option>
</select>
</div>
</div>
<div v-else>
<div class="option-row">
<label>Data Source:</label>
<input id="txtFormula" type="text" v-model="dataSource" />
</div>
<div class="option-row">
<label>Binding Text:</label>
<input id="txtText" type="text" v-model="text" />
</div>
<div class="option-row">
<label>Binding Value:</label>
<input id="txtValue" type="text" v-model="value" />
</div>
</div>
</div>
<div class="option-row">
<label for="itemHeight">Item Height:</label>
<input id="itemHeight" type="text" v-model="itemHeight" />
</div>
<div class="option-row">
<input id="editable" type="checkbox" v-model="editable" />
<label for="editable">Editable:</label>
</div>
<div class="option-row">
<input id="allowFloat" type="checkbox" v-model="allowFloat" />
<label for="allowFloat">Allow Float:</label>
</div>
<div class="option-row">
<input type="button" id="setProperty" value="Update" :disabled="disabled"
@click="propertyChange($event, true)" />
</div>
</div>
</div>
</template>
<script setup>
import '@mescius/spread-sheets-vue'
import { ref, computed } from 'vue';
import GC from '@mescius/spread-sheets';
import '@mescius/spread-sheets-tablesheet';
const spreadNS = GC.Spread.Sheets;
function Country(shortName, fullName) {
this.value = this.shortName = shortName;
this.text = this.fullName = fullName;
}
function addLoadingTip() {
const div = document.createElement('div');
div.style.position = 'absolute';
div.style.inset = '0';
div.style.display = 'flex';
div.style.alignItems = 'center';
div.style.justifyContent = 'center';
div.style.background = 'white';
div.style.zIndex = '100';
div.textContent = 'Loading data from server ...';
document.body.appendChild(div);
return div;
}
function dataBindingToDataBindingEditorValue(dataBinding, workBook) {
let dataBindingEditorValue;
const defDataSource = getDefaultDataSource(workBook);
if (!dataBinding) {
dataBindingEditorValue = defDataSource;
} else {
const dataSourceType = isDataTable(dataBinding.dataSource, workBook) ? 0 : 1;
if (dataSourceType === 0) {
dataBindingEditorValue = {
dataSourceType: dataSourceType,
tableName: dataBinding.dataSource,
textColumn: dataBinding.text,
valueColumn: dataBinding.value,
};
} else { // custom
dataBindingEditorValue = {
...defDataSource,
dataSourceType: dataSourceType,
dataSource: dataBinding.dataSource,
text: dataBinding.text,
value: dataBinding.value,
};
}
}
return dataBindingEditorValue;
}
function getDefaultDataSource(workBook) {
const tables = getDataTables(workBook);
if (tables.length === 0) {
return { dataSourceType: 0 };
}
const column = getColumns(tables[0], workBook)[0];
return { dataSourceType: 0, tableName: tables[0], textColumn: column, valueColumn: column };
}
function dataBindingEditorValueToDataBinding(uiData) {
if (+uiData.dataSourceType === 0) {
return { dataSource: uiData.tableName, text: uiData.textColumn, value: uiData.valueColumn };
} else {
return { dataSource: uiData.dataSource, text: uiData.text, value: uiData.value };
}
}
function isDataTable(table, workBook) {
const lowerTableName = table.toLowerCase();
return getDataTables(workBook).some((t) => t.toLowerCase() === lowerTableName);
}
function getDataTables(workBook) {
if (!workBook) {
return [];
}
const dataManager = workBook.dataManager();
if (!dataManager) {
return [];
}
const tables = workBook.dataManager().tables;
if (!tables) {
return [];
}
return Object.keys(tables);
}
function getColumns(tableName, workBook) {
if (!workBook) {
return [];
}
const tables = workBook.dataManager().tables;
if (!tables) {
return [];
}
const table = getTableIgnoreCase(tables, tableName);
if (!table) {
return [];
}
return Object.keys(table.columns);
}
function getTableIgnoreCase(tables, tableName) {
if (!tableName) {
return tables[0];
}
const lowerTableName = tableName.toLowerCase();
for (const key in tables) {
if (tables.hasOwnProperty(key) && key.toLowerCase() === lowerTableName) {
return tables[key];
}
}
return null;
}
const editorValueType = ref(0);
const itemsText = ref('');
const itemsValue = ref('');
const itemHeight = ref(0);
const editable = ref(false);
const allowFloat = ref(true);
const disabled = ref(false);
const editorValueTypeList = Object.keys(GC.Spread.Sheets.CellTypes.EditorValueType).filter(key => isNaN(Number(key)));
const bindingType = ref(0);
const dataSourceType = ref(0);
const tableName = ref('');
const textColumn = ref('');
const valueColumn = ref('');
const dataSource = ref('');
const text = ref('');
const value = ref('');
const bindingTypeList = ['Static Items', 'Data Binding'];
const dataSourceTypeList = ['Table', 'Custom'];
let mySpread;
const tableNameList = computed(() => getDataTables(mySpread));
const columnNameList = computed(() => getColumns(tableName.value, mySpread));
const initSpread = async (spreadInstance) => {
mySpread = spreadInstance;
mySpread.suspendPaint();
const loadingTip = addLoadingTip();
const res = await fetch('$DEMOROOT$/en/sample/features/cells/cell-types/combobox/spread.json');
await mySpread.fromJSON(await res.json());
mySpread.setSheetCount(2);
const sheet1 = mySpread.getSheet(0);
initStaticItemsSheet(sheet1);
const sheet2 = mySpread.getSheet(1);
initDataBindingItemsSheet(sheet2);
fetchDataSource(mySpread);
mySpread.resumePaint();
loadingTip.remove();
};
const fetchDataSource = (spreadInstance) => {
const productsSheets = spreadInstance.addSheetTab(0, 'Products', GC.Spread.Sheets.SheetType.tableSheet);
productsSheets.options.allowAddNew = false;
const productsTable = spreadInstance.dataManager().tables.Products;
productsTable.fetch().then(() => {
const view = productsTable.addView("myView", Object.keys(productsTable.columns).map(c => ({ value: c, width: 150 })));
productsSheets.setDataView(view);
});
const customerSheets = spreadInstance.addSheetTab(1, 'Customers', GC.Spread.Sheets.SheetType.tableSheet);
customerSheets.options.allowAddNew = false;
const customersTable = spreadInstance.dataManager().tables.Customers;
customersTable.fetch().then(() => {
const view = customersTable.addView("myView", Object.keys(customersTable.columns).map(c => ({ value: c, width: 150 })));
customerSheets.setDataView(view);
});
const employeesSheets = spreadInstance.addSheetTab(2, 'Employees', GC.Spread.Sheets.SheetType.tableSheet);
employeesSheets.options.allowAddNew = false;
const employeesTable = spreadInstance.dataManager().tables.Employees;
employeesTable.fetch().then(() => {
const view = employeesTable.addView("myView", Object.keys(employeesTable.columns).map(c => ({ value: c, width: 150 })));
employeesSheets.setDataView(view);
});
spreadInstance.setActiveSheetIndex(0);
};
const tableNameChanged = () => {
const columns = getColumns(tableName.value, mySpread);
textColumn.value = columns[0];
valueColumn.value = columns[0];
};
const propertyChange = (e, settings) => {
const sheet = mySpread.getActiveSheet();
const sels = sheet.getSelections();
if (sels && sels.length > 0) {
const sel = getActualRange(sels[0], sheet.getRowCount(), sheet.getColumnCount());
const comboBoxCellType = sheet.getCellType(sel.row, sel.col);
if (!(comboBoxCellType instanceof spreadNS.CellTypes.ComboBox)) {
disabled.value = true;
return;
}
if (!settings) {
disabled.value = false;
editorValueType.value = comboBoxCellType.editorValueType();
const items = comboBoxCellType.items();
const { texts, values } = getTextAndValueStringArray(items);
itemsText.value = texts;
itemsValue.value = values;
editable.value = comboBoxCellType.editable();
itemHeight.value = comboBoxCellType.itemHeight();
allowFloat.value = comboBoxCellType.allowFloat();
const dataBinding = comboBoxCellType.dataBinding();
if (!dataBinding) {
bindingType.value = 0;
} else {
bindingType.value = 1;
}
const dataBindingEditorValue = dataBindingToDataBindingEditorValue(dataBinding, mySpread);
dataSourceType.value = dataBindingEditorValue.dataSourceType;
tableName.value = dataBindingEditorValue.tableName;
textColumn.value = dataBindingEditorValue.textColumn;
valueColumn.value = dataBindingEditorValue.valueColumn;
dataSource.value = dataBindingEditorValue.dataSource;
text.value = dataBindingEditorValue.text;
value.value = dataBindingEditorValue.value;
} else {
comboBoxCellType.editorValueType(Number(editorValueType.value));
const itemsTextArray = itemsText.value.split(",");
const itemsValueArray = itemsValue.value.split(",");
const itemsLength = itemsTextArray.length > itemsValueArray.length ? itemsTextArray.length : itemsValueArray.length;
const items = getTextAndValueArray(itemsTextArray, itemsValueArray, itemsLength);
comboBoxCellType.items(items);
comboBoxCellType.editable(editable.value);
comboBoxCellType.allowFloat(allowFloat.value);
const itemHeightNumber = Number(itemHeight.value);
if (!isNaN(itemHeightNumber) && itemHeightNumber > 0) {
comboBoxCellType.itemHeight(itemHeightNumber);
}
if (+bindingType.value === 1) {
const dataBinding = dataBindingEditorValueToDataBinding(
{
dataSourceType: dataSourceType.value,
tableName: tableName.value,
textColumn: textColumn.value,
valueColumn: valueColumn.value,
dataSource: dataSource.value,
text: text.value,
value: value.value
});
comboBoxCellType.dataBinding(dataBinding);
} else {
comboBoxCellType.dataBinding(null);
}
}
}
sheet.repaint();
};
const getActualRange = (range, maxRowCount, maxColCount) => {
const row = range.row < 0 ? 0 : range.row;
const col = range.col < 0 ? 0 : range.col;
const rowCount = range.rowCount < 0 ? maxRowCount : range.rowCount;
const colCount = range.colCount < 0 ? maxColCount : range.colCount;
return new spreadNS.Range(row, col, rowCount, colCount);
};
const getTextAndValueStringArray = (items) => {
let texts = '', values = '';
for (let i = 0, len = items.length; i < len; i++) {
const item = items[i];
if (!item) {
continue;
}
if (item.text) {
texts += item.text + ',';
}
if (item.value) {
values += item.value + ',';
}
}
texts = texts.slice(0, texts.length - 1);
values = values.slice(0, values.length - 1);
return { texts, values };
};
const getTextAndValueArray = (itemsText, itemsValue, itemsLength) => {
const items = [];
for (let count = 0; count < itemsLength; count++) {
const t = itemsText.length > count && itemsText[0] !== "" ? itemsText[count] : undefined;
const v = itemsValue.length > count && itemsValue[0] !== "" ? itemsValue[count] : undefined;
if (t !== undefined && v !== undefined) {
items[count] = { text: t, value: v };
} else if (t !== undefined) {
items[count] = { text: t };
} else if (v !== undefined) {
items[count] = { value: v };
}
}
return items;
};
const initStaticItemsSheet = (sheet) => {
sheet.name("Static-Items");
sheet.bind(spreadNS.Events.SelectionChanged, (e) => propertyChange(e));
sheet.suspendPaint();
sheet.setColumnWidth(2, 120);
sheet.setColumnWidth(1, 200);
const combo = new spreadNS.CellTypes.ComboBox();
combo.items([{ text: "Oranges", value: "11k" }, { text: "Apples", value: "15k" }, { text: "Grape", value: "100k" }])
.editorValueType(spreadNS.CellTypes.EditorValueType.text);
sheet.setValue(0, 3, "Result:");
sheet.getCell(1, 2, spreadNS.SheetArea.viewport).cellType(combo).value("Apples");
sheet.setValue(1, 1, "ComboBoxCellType");
sheet.setFormula(1, 3, "=C2");
const editableCombo = new spreadNS.CellTypes.ComboBox(),
data = [new Country("CN", "China"), new Country("JP", "Japan"), new Country("US", "United States")];
editableCombo.editable(true)
.items(data)
.itemHeight(24)
.editorValueType(spreadNS.CellTypes.EditorValueType.value);
sheet.getCell(3, 2, spreadNS.SheetArea.viewport).cellType(editableCombo).value("US");
sheet.setValue(3, 1, "Editable ComboBoxCellType");
sheet.setFormula(3, 3, "=C4");
const allowFloatCombo = new spreadNS.CellTypes.ComboBox();
allowFloatCombo.items(Array.from({ length: 100 }, (_, index) => {
return { text: index + 1, value: index + 1 }
}));
sheet.getCell(22, 2).cellType(allowFloatCombo);
sheet.setValue(22, 1, "Try Allow Float ComBoxCellType");
sheet.setActiveCell(1, 2);
propertyChange(null);
sheet.resumePaint();
};
const initDataBindingItemsSheet = (sheet) => {
sheet.name("Binding-Items");
sheet.bind(spreadNS.Events.SelectionChanged, (e) => propertyChange(e));
sheet.suspendPaint();
sheet.setColumnWidth(1, 200);
sheet.setColumnWidth(2, 200);
sheet.setColumnWidth(3, 200);
// --------------------Binding to Table--------------------
let combo = new spreadNS.CellTypes.ComboBox();
combo.dataBinding({ dataSource: "Products", text: "productName", value: "productId" });
combo.editorValueType(spreadNS.CellTypes.EditorValueType.text);
sheet.setValue(0, 3, "Result:");
sheet.getCell(1, 2, spreadNS.SheetArea.viewport).cellType(combo).value("Chang");
sheet.setValue(1, 1, "Binding to Table");
sheet.setFormula(1, 3, "=C2");
// --------------------Binding to a formula--------------------
const editableCombo = new spreadNS.CellTypes.ComboBox();
editableCombo.editable(true)
.dataBinding({ dataSource: '=SORT(UNIQUE(QUERY("Products", {"productName","productId"})))', text: 0, value: 1 })
.itemHeight(24)
.editorValueType(spreadNS.CellTypes.EditorValueType.value);
sheet.getCell(3, 2, spreadNS.SheetArea.viewport).cellType(editableCombo).value(1);
sheet.setValue(3, 1, "Binding to a formula");
sheet.setFormula(3, 3, "=C4");
// --------------------Binding to a range--------------------
sheet.setArray(6, 6, [["Oranges", "11k"], ["Apples", "15k"], ["Grape", "100k"]])
combo = new spreadNS.CellTypes.ComboBox();
combo.editorValueType(spreadNS.CellTypes.EditorValueType.value);
combo.dataBinding({ dataSource: "'Binding-Items'!G7:H9", text: 0, value: 1 });
sheet.getCell(5, 2, spreadNS.SheetArea.viewport).cellType(combo).value("15k");
sheet.setValue(5, 1, "Binding to range");
sheet.setFormula(5, 3, "=C6");
sheet.setActiveCell(1, 2);
propertyChange(null);
sheet.resumePaint();
};
</script>
<style scoped>
#app {
height: 100%;
}
.sample-tutorial {
position: relative;
height: 100%;
overflow: hidden;
}
.sample-spreadsheets {
width: calc(100% - 280px);
height: 100%;
overflow: hidden;
float: left;
}
.options-container {
float: right;
width: 280px;
overflow: auto;
padding: 12px;
height: 100%;
box-sizing: border-box;
background: #fbfbfb;
}
.option-row {
padding-bottom: 12px;
}
label {
padding-bottom: 4px;
display: block;
}
input,
select {
width: 100%;
padding: 4px 8px;
box-sizing: border-box;
}
input[type=checkbox] {
width: auto;
}
input[type=checkbox]+label {
display: inline-block;
width: auto;
user-select: none;
}
body {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
<!DOCTYPE html>
<html style="height:100%;font-size:14px;">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>SpreadJS VUE</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css"
href="$DEMOROOT$/en/vue3/node_modules/@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css">
<script src="$DEMOROOT$/en/vue3/node_modules/systemjs/dist/system.src.js"></script>
<script src="./systemjs.config.js"></script>
<script src="./compiler.js" type="module"></script>
<script>
var System = SystemJS;
System.import("./src/app.js");
System.import('$DEMOROOT$/en/lib/vue3/license.js');
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>
export function getData() {
return [
{ name: "Stoves S0", line: "Washers", color: "Green", discontinued: true, rating: "Average" },
{ name: "Computers C1", line: "Washers", color: "Green", discontinued: true, rating: "Average" },
{ name: "Washers W3", line: "Washers", color: "Green", discontinued: true, rating: "Average" }
]
}
(function (global) {
SystemJS.config({
transpiler: 'plugin-babel',
babelOptions: {
es2015: true
},
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
packageConfigPaths: [
'./node_modules/*/package.json',
"./node_modules/@mescius/*/package.json",
"./node_modules/@babel/*/package.json",
"./node_modules/@vue/*/package.json"
],
map: {
'vue': "npm:vue/dist/vue.esm-browser.js",
'tiny-emitter': 'npm:tiny-emitter/index.js',
'plugin-babel': 'npm:systemjs-plugin-babel/plugin-babel.js',
"systemjs-babel-build": "npm:systemjs-plugin-babel/systemjs-babel-browser.js",
'@mescius/spread-sheets': 'npm:@mescius/spread-sheets/index.js',
'@mescius/spread-sheets-tablesheet': 'npm:@mescius/spread-sheets-tablesheet/index.js',
'@mescius/spread-sheets-resources-en': 'npm:@mescius/spread-sheets-resources-en/index.js',
'@mescius/spread-sheets-vue': 'npm:@mescius/spread-sheets-vue/index.js'
},
meta: {
'*.css': { loader: 'systemjs-plugin-css' },
'*.vue': { loader: "../plugin-vue/index.js" }
}
});
})(this);