콤보 상자

ComboBox는 콤보 상자 셀을 나타냅니다. 이는 양식에 데이터를 입력할 때와 같이 사용자가 항목을 선택할 수 있는 제한된 목록을 추가하려는 경우에 유용할 수 있습니다.

설명
app.vue
index.html
data.js

콤보 상자 셀을 만들려면 다음 예를 따르십시오:

    var combo = new GC.Spread.Sheets.CellTypes.ComboBox();
    sheet.setCellType(3, 2, combo, GC.Spread.Sheets.SheetArea.viewport);

editorValueType 메서드를 사용하여 기본 데이터 모델에 기록된 값을 가져오고 설정할 수 있습니다. 편집기 값 유형은 EditorValueType 열거입니다.

  • text: 선택된 항목의 텍스트 값을 모델에 씁니다.
  • index: 선택된 항목의 색인을 모델에 씁니다.
  • value: 선택된 항목의 해당 데이터 값을 모델에 씁니다.
    combo.editorValueType(GC.Spread.Sheets.CellTypes.EditorValueType.text);

다른 editorValueType 설정은 다른 유형의 편집기 값을 만듭니다. 콤보 상자의 값은 콤보 상자의 드롭다운 목록 항목에 따라 다릅니다. items 메서드를 사용하여 항목을 가져오고 설정할 수 있습니다. 예:

    combo.items([
     { text: 'Oranges', value: '11k' },
     { text: 'Apples', value: '15k' },
     { text: 'Grape', value: '100k' }]);

dataBinding 메서드를 사용하여 콤보 상자를 데이터 소스에 바인딩할 수도 있습니다. 데이터 소스는 런타임에 콤보 상자의 항목을 대체합니다. 예를 들어:

    var dataSource = { dataSource: "Products", text: "productName", value: "productId" };
    combo.dataBinding(dataSource);

editable 메서드를 사용하여 사용자가 콤보 상자 편집기에 입력할 수 있는지 여부를 설정합니다. 기본값은 false입니다. 선택만 허용됩니다. 예:

    editableCombo.editable(true);

itemHeight 메서드를 사용하여 드롭다운 목록에서 각 항목의 높이를 설정할 수 있습니다. 예:

    combo.itemHeight(24);

allowFloat 메서드를 사용해 드롭다운 목록이 Spread 외부에 떠 있도록 허용할지 설정하십시오.

    combo.allowFloat(false);
콤보 상자 셀을 만들려면 다음 예를 따르십시오: editorValueType 메서드를 사용하여 기본 데이터 모델에 기록된 값을 가져오고 설정할 수 있습니다. 편집기 값 유형은 EditorValueType 열거입니다. text: 선택된 항목의 텍스트 값을 모델에 씁니다. index: 선택된 항목의 색인을 모델에 씁니다. value: 선택된 항목의 해당 데이터 값을 모델에 씁니다. 다른 editorValueType 설정은 다른 유형의 편집기 값을 만듭니다. 콤보 상자의 값은 콤보 상자의 드롭다운 목록 항목에 따라 다릅니다. items 메서드를 사용하여 항목을 가져오고 설정할 수 있습니다. 예: dataBinding 메서드를 사용하여 콤보 상자를 데이터 소스에 바인딩할 수도 있습니다. 데이터 소스는 런타임에 콤보 상자의 항목을 대체합니다. 예를 들어: editable 메서드를 사용하여 사용자가 콤보 상자 편집기에 입력할 수 있는지 여부를 설정합니다. 기본값은 false입니다. 선택만 허용됩니다. 예: itemHeight 메서드를 사용하여 드롭다운 목록에서 각 항목의 높이를 설정할 수 있습니다. 예: allowFloat 메서드를 사용해 드롭다운 목록이 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'; import '@mescius/spread-sheets-resources-ko'; GC.Spread.Common.CultureManager.culture("ko-kr"); 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$/ko/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$/ko/vue3/node_modules/@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css"> <script src="$DEMOROOT$/ko/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$/ko/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-resources-ko': 'npm:@mescius/spread-sheets-resources-ko/index.js', '@mescius/spread-sheets-tablesheet': 'npm:@mescius/spread-sheets-tablesheet/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);