0
我有下面的代碼示例同我能讀懂我的Excel文件,其中:如何閱讀特定的Excel列值的使用將它們放在字符串數組C#2.0
private bool excelvalidate(string requestType, string filename)
{
Excel.Application ExcelObj = null;
ExcelObj = new Excel.Application();
Excel.Range range = null;
Excel.Workbook theWorkbook = null;
Excel.Sheets sheets = null;
Excel.Worksheet worksheet = null;
bool strValResult = false;
string[] strArray = null;
if (ExcelObj != null)
{
theWorkbook = ExcelObj.Workbooks.Open("D:/Support/" + filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
sheets = theWorkbook.Worksheets;
worksheet = (Excel.Worksheet)sheets.get_Item(1);
for (int x = 1; x <= 1; x++)
{
range = worksheet.get_Range("A" + x.ToString(), "G" + x.ToString());
System.Array myvalues = (System.Array)range.Cells.get_Value(null);
strArray = ConvertToStringArray(myvalues);
}
if (requestType == "CreateCityKeys" || requestType == "CreateCityShortKeys")
{
strValResult = CheckStringInArray("City Name", strArray);
if (strValResult == true)
{
//Here I want to call a function which will return all the column values in City Name something like below
string [] columnArray = ReadAllValuesFromColumn("City Name");
}
}
else if (requestType == "CreateAirportKeys")
{
strValResult = CheckStringInArray("Full Airport Name", strArray);
}
else if (requestType == "CreateAirportShortKeys")
{
strValResult = CheckStringInArray("Airport Short Name", strArray);
}
ExcelObj.Workbooks.Close();
ExcelObj.Quit();
ExcelObj = null;
theWorkbook = null;
sheets = null;
range = null;
Marshal.ReleaseComObject(theWorkbook);
}
return strValResult;
}
private bool CheckStringInArray(string chkstr, string[] strArr)
{
bool exists = false;
foreach (string x in strArr)
{
if (x.Contains(chkstr))
{
exists = true;
}
}
return exists;
}
private string[] ConvertToStringArray(System.Array values)
{
// create a new string array
string[] theArray = new string[values.Length];
// loop through the 2-D System.Array and populate the 1-D String Array
for (int i = 1; i <= values.Length; i++)
{
if (values.GetValue(1, i) == null)
theArray[i - 1] = "";
else
theArray[i - 1] = (string)values.GetValue(1, i).ToString();
}
return theArray;
}
在上面的代碼中,你可以看到是,我想打電話給如下功能:
string [] columnArray = ReadAllValuesFromColumn("City Name");
請建議的邏輯寫上面的函數,如果我通過列標題名稱爲「城市名稱」
PLE閱讀所有的列值ase建議使用一些代碼片段。
謝謝