将Excel行,列导入列表 [英] Import Excel Rows, Columns into List
问题描述
我正在寻找一种将Excel工作表的某些元素导入到列表中的方法.我的目标是能够对excel工作表的属性(第一行)进行排序(单击我要查看的属性),并获取第一行下方的行的值.
I am looking for a way to import certain elements of an Excel sheet into a List. My goal is to be able to sort the attributes (first row) of the excel sheet (click on the attribute I want to see) and get the values of the rows below the first row.
推荐答案
我将以这种方式实现您想要的内容,而不使用Sheet
接口但使用Worksheet
类对象.
I would implement what you want this way without using Sheet
Interface but Worksheet
class object.
要注意的一件事是,我在二维数组中获得所有使用的范围后关闭了excel工作表.这将使其更快,否则范围的读数将慢很多.有很多方法可以使其变得更快.
One thing to note is I am closing the excel sheet after I get all the used range in 2-d array. This makes it faster otherwise the reading from range will be a lot slower. There could be a lot many ways to make it even faster.
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行,列导入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!