如何在excel中将一列数据存储到C#中的string []

时间:2015-12-25 11:14:35

标签: c# string excel vsto excel-interop

我有一个像这样的字符串[]成员:

private string[] mStrings = null;

和构造函数中的代码如下:

Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkBook = excelApp.Workbooks.Open(excel_file_path);
Excel.Worksheet excelWorkSheet = (Excel.Worksheet)excelWorkBook.Sheets[2]; // I get the data from the second sheet

我想将列F中的数据存储到mStrings中,所以我写了这样的代码:

mStrings = excelWorkSheet.Columns["F"].Value2;

这段代码错了,那么什么是正确的代码?谢谢!

1 个答案:

答案 0 :(得分:1)

可能有更好的解决方法,但我设法通过在列中获取UsedRange然后使用简单的'for'循环遍历列来解决您的问题,将值存储到字符串List然后传递List到一个字符串数组

        string[] mColumn = null;
        List<string> mlstColumn = new List<string>();

        // get used range of column F
        Range range = excelWorkSheet.UsedRange.Columns["F", Type.Missing];

        // get number of used rows in column F
        int rngCount = range.Rows.Count;

        // iterate over column F's used row count and store values to the list
        for (int i = 1; i <= rngCount; i++)
        {
            mlstColumn.Add(excelWorkSheet.Cells[i, "F"].Value.ToString());
        }

        // List<string> --> string[]
        mColumn = mlstColumn.ToArray();

        // remember to Quit() or the instance of Excel will keep running in the background
        excelApp.Quit();