使用C#的Microsoft.Office.Interop.Excel

时间:2017-03-20 17:01:34

标签: c# excel office-interop com-interop excel-interop

我想从我的Excel应用程序生成C#文件,用户稍后可以填写该文件。我使用Microsoft.Office.Interop.Excel

我启动Excel并使用以下代码填充标题单元格:

var excelApp = new Excel.Application {Visible = true};
var workbook = excelApp.Workbooks.Add(Missing.Value);
var workSheet = (Excel.Worksheet) workbook.Worksheets.Item[1];

headers.Select((s, i) => new Tuple<string, int>(s, i)).ToList().ForEach
    (
     h => { workSheet.Cells[1, h.Item2 + 1] = h.Item1; }
    );

如何指定第一列的单元格应该包含包含预先填充值的下拉列表?

我已经尝试过在线提供的大量内容,例如下面找到的here,但没有运气:

var dropDownRange = workSheet.Range["A2"].Resize[64000];
dropDownRange.Value = Values;
dropDownRange = dropDownRange.Offset[0, 1];
dropDownRange.Validation.Delete();
dropDownRange.Validation.Add(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertInformation, Type.Missing, "=DropDownList");

1 个答案:

答案 0 :(得分:1)

在将验证限制应用于列表时,formula参数需要以逗号分隔的值字符串。下面是一个使用三个值创建下拉列表的示例:

var items = new List<string>() { "Item 1", "Item 2", "Item 3" };
var formattedItems = string.Join(", ", items.ToArray());

var dropDownRange = workSheet.Range["A2"].EntireColumn;
dropDownRange.Validation.Delete();
dropDownRange.Validation.Add(Excel.XlDVType.xlValidateList,
    Excel.XlDVAlertStyle.xlValidAlertInformation,
    Excel.XlFormatConditionOperator.xlBetween,
    formattedItems,
    Type.Missing);

此外,如果您需要将单元格默认为值,则可以执行以下操作:

dropDownRange.Value = "Item 2";

甚至更好:

dropDownRange.Value = items[1];