如何在C#中将excel中的一列数据存储到string[]中
How to store a column of data in excel to string[] in C#
我有一个这样的 string[] 成员:
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;
这段代码是错误的,那么正确的代码是什么?谢谢!
可能有更好的方法来解决这个问题,但我设法解决了你的问题,方法是在列中获取 UsedRange,然后使用简单的 'for' 循环遍历该列,将值存储到列表中字符串,然后将列表传递给字符串数组
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();
我有一个这样的 string[] 成员:
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;
这段代码是错误的,那么正确的代码是什么?谢谢!
可能有更好的方法来解决这个问题,但我设法解决了你的问题,方法是在列中获取 UsedRange,然后使用简单的 'for' 循环遍历该列,将值存储到列表中字符串,然后将列表传递给字符串数组
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();