简体   繁体   English

如何在Excel中创建自动补全功能?

[英]How to create autocompletion in Excel?

In my application, there is a need to create an excel file which should have an auto-completion feature. 在我的应用程序中,需要创建一个具有自动完成功能的Excel文件。 Suppose I am fetching some values "Data 1","Data 2" from the database, after fetching I want to bind those values to a particular column of excel. 假设我要从数据库中获取一些值“ Data 1”,“ Data 2”,在获取之后,我想将这些值绑定到excel的特定列。 So when a user types something it would prompt "Data 1","Data 2"... 因此,当用户键入内容时,将提示“数据1”,“数据2” ...

How to achieve this? 如何实现呢? help needed 需要帮助

You are describing a feature called Data Validation. 您正在描述一种称为数据验证的功能。 It's main purpose is to limit the possible values of a cell to a certain range but, as you have spotted, this has the handy side-effect of having Excel show a drop down of the available values. 它的主要目的是将单元格的可能值限制在一定范围内,但是,正如您已经发现的那样,这具有使Excel显示可用值下降的便捷副作用。

You can do something like this using various openXML libraries which allow you to create .xlsx files in .NET code. 您可以使用各种openXML库执行类似的操作,这些库允许您在.NET代码中创建.xlsx文件。 I like EPPlus which would let you do something like this: 我喜欢EPPlus ,它会让您执行以下操作:

static void Main(string[] args)
{
    var fInfo = new FileInfo("output.xlsx");
    using (var excel = new ExcelPackage())
    {
        var sht1 = excel.Workbook.Worksheets.Add("DataSheet1");
        sht1.Cells[1,1].Value = "Occupation:";
        var validation = sht1.DataValidations.AddListValidation("A2");
        foreach(var allowedValue in GetAllowedValues())
        {
            validation.Formula.Values.Add(allowedValue);
        }
        excel.SaveAs(fInfo);
    }
}

private static IEnumerable<string> GetAllowedValues()
{
    return new string []{"Doctor","Baker","Candlestick Maker"};
} 

This gives the dropdown list you are referring to (my screengrab is from LibreOffice but you will see the same effect in Excel): 这给出了您要引用的下拉列表(我的屏幕抓图来自LibreOffice,但您将在Excel中看到相同的效果):

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM