使用c#在Excel工作表中创建列的所有行作为下拉列表

时间:2015-02-12 10:04:27

标签: c# excel xls

我的要求是导出一个包含3列的空白Excel工作表,其中所有行的第一列作为下拉列表,以便用户可以使用此工作表根据需要修改数据。我正在使用c#导出文件。

我已经处理过了,但目前它只在特定单元格中创建了一个下拉列表,但我想将第一列的所有行作为下拉列表。

以下是我正在使用的代码:

object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application app;
Microsoft.Office.Interop.Excel.Worksheet wksheet;
Microsoft.Office.Interop.Excel.Workbook wkbook;
app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
wkbook = app.Workbooks.Add(true);
wksheet = (Microsoft.Office.Interop.Excel.Worksheet)wkbook.ActiveSheet;
string[] ddl_item = 
{
    "Answers",
    "Autos",
    "Finance",
    "Games",
    "Groups",
    "HotJobs",
    "Maps",
    "Mobile Web",
    "Movies",
    "Music",
    "Personals",
    "Real Estate",
    "Shopping",
    "Sports",
    "Tech",
    "Travel",
    "TV",
    "Yellow Pages"
};
Microsoft.Office.Interop.Excel.Range xlsRange;
xlsRange = wksheet.get_Range("A1", "A1");

Microsoft.Office.Interop.Excel.DropDowns xlDropDowns;
Microsoft.Office.Interop.Excel.DropDown xlDropDown;

xlDropDowns = ((Microsoft.Office.Interop.Excel.DropDowns)(wksheet.DropDowns(oMissing)));
xlDropDown = xlDropDowns.Add((double)xlsRange.Left, (double)xlsRange.Top, (double)xlsRange.Width, (double)xlsRange.Height, true);

//Add item into drop down list
for (int i = 0; i < ddl_item.Count(); i++)
{
    xlDropDown.AddItem(ddl_item[i], i + 1);
}
app.Visible = true;

1 个答案:

答案 0 :(得分:1)

我刚刚看到你的问题,这有点晚了,但你的问题在你的范围内,你可以改变你的代码来满足你的需求:

        //change your range
        Range range = worksheet.UsedRange;
        //this part makes all the in-range rows of first column as a dropdown list
        int row;
        for (row = 1; row <= range.Rows.Count; row++)
        {
            xlDropDowns = ((DropDowns) (worksheet.DropDowns(Type.Missing)));
            xlDropDown = xlDropDowns.Add((double) range[row, 1].Left, (double) range[row, 1].Top,
                (double) range[row, 1].Width, (double) range[row, 1].Height, true);
            string[] ddl_item =
            {
                "Answers",
                "Autos",
                "Finance",
                "Games",
                "Groups",
                "HotJobs",
                "Maps",
                "Mobile Web",
                "Movies",
                "Music",
                "Personals",
                "Real Estate",
                "Shopping",
                "Sports",
                "Tech",
                "Travel",
                "TV",
                "Yellow Pages"
            };
            for (int i = 0; i < ddl_item.Count(); i++)
            {
                xlDropDown.AddItem(ddl_item[i], i + 1);
            }
        }
相关问题