设置excel下拉框优化?

作者站长头像
站长
· 阅读数 44

背景:

技术栈:项目: vue3 + vite

   导出excel库:exceljs

场景: 希望导出的excel的某一列填充下拉框内容,例如设置excel下拉框优化?

尝试:相关代码如下

for(let i = 2; i< 500;i++) {
    const cellIndex = `B${i}`
    _sheet1.getCell(cellIndex).dataValidation = {
    type: 'list',
    allowBlank: true,
    showInputMessage: true,  
    showErrorMessage: true,  
    showDropDownArrow: true,  
    errorTitle: '错误',  
    error: '请从下拉列表中选择一个有效的项',  
    promptTitle: '选择',  
    prompt: '请从下拉列表中选择' ,
    formulae: ['"软件一班,软件二班,软件三班"'],
  };
  }

上述代码一次只能给某一个单元格加下拉框,所以要达到使B列单元格都加上下拉框的目的,就要给一个很大的终止值,去循环遍历。有没有什么更好的方法去优化?

回复
1个回答
avatar
test
2024-06-20

确实不太友好,文档中只有 getCell().dataValidation 一种示例。但是可以从仓库 Issue 里面发现还有 ws.dataValidations.add() 这种方式。

更加简单粗暴一些:

worksheet.dataValidations.add(
  'A2:A9999', 
  {
    type: 'list', 
    allowBlank: false, 
    formulae: ['"One,Two,Three,Four"'], 
    showErrorMessage: true, 
    errorStyle: 'error', 
    error: 'Please select a valid value from the list' 
  }
)

[F] Table Data Validation on columns · exceljs/exceljs · Discussion #2461

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容