导入Excel行,列成列表
问题描述:
我正在寻找一种将Excel工作表的某些元素导入列表的方法。我的目标是能够对excel工作表的属性(第一行)进行排序(单击我想查看的属性)并获取第一行下面的行的值。导入Excel行,列成列表
答
我会实现你想要的这种方式,而不使用Sheet
接口,但Worksheet
类对象。
有一点需要注意的是,在我获得二维数组中所有使用的范围之后,我正在关闭Excel表格。这使得速度更快,否则从范围读取会慢很多。可能有很多方法可以让它更快。
Application xlApp = new Application();
Workbook xlWorkBook = null;
Worksheet dataSheet = null;
Range dataRange = null;
List<string> columnNames = new List<string>();
object[,] valueArray;
try
{
// Open the excel file
xlWorkBook = xlApp.Workbooks.Open(fileFullPath, 0, true);
if (xlWorkBook.Worksheets != null
&& xlWorkBook.Worksheets.Count > 0)
{
// Get the first data sheet
dataSheet = xlWorkBook.Worksheets[1];
// Get range of data in the worksheet
dataRange = dataSheet.UsedRange;
// Read all data from data range in the worksheet
valueArray = (object[,])dataRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);
if (xlWorkBook != null)
{
// Close the workbook after job is done
xlWorkBook.Close();
xlApp.Quit();
}
for (int colIndex = 0; colIndex < valueArray.GetLength(1); colIndex++)
{
if (valueArray[0, colIndex] != null
&& !string.IsNullOrEmpty(valueArray[0, colIndex].ToString()))
{
// Get name of all columns in the first sheet
columnNames.Add(valueArray[0, colIndex].ToString());
}
}
}
// Now you have column names or to say first row values in this:
// columnNames - list of strings
}
catch (System.Exception generalException)
{
if (xlWorkBook != null)
{
// Close the workbook after job is done
xlWorkBook.Close();
xlApp.Quit();
}
}
您是否添加了excel作为参考? – BugFinder
可能的重复[我得到“缺少一个使用指令或程序集引用”,并没有线索发生了什么问题](https://*.com/questions/17344295/im-getting-the-missing-a-using -directive-or-assembly-reference-and-no-clue-wh) – SeM
你不需要写'Excel.Sheets'。你已经使用了指令'Excel',所以只需要写一个接口的'Sheet'即可。否则,您可以使用具体的类“工作表”。 – praty