用C#中的excel数据创buildHashMap

我是新来的C#和我有一个Excel列表2列,我想创build一个哈希表在该表中的date。 比方说excel表单看起来像

A Value1 A Value2 A Value3 B value4 B value5 

其中A和B在第一列中,第二列中的值

我想要创build一个hashmap

 HashMap<String, List<String>>(); 

其中string将是关键,List将是该关键字的值

有什么想法吗?

谢谢

我正在使用这篇文章作为参考。 所以,你正在寻找的可能是这样的:

看看我如何使用字典,而不是一个HashMap

 //import the references needed. Checkout the article public static void getExcelFile() { //Create COM Objects. Create a COM object for everything that is referenced Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\wearybands\test.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; //IMPORTANT SECTION var dictionary = new Dictionary<string, List<string>>(); //iterate over the rows and columns as it appears in the file //excel is not zero based!! for (int i = 1; i <= rowCount; i++) { //it would be nice if we add some null checking to these variables //so, check the article var col1 = xlRange.Cells[i, 1].Value2.ToString(); var col2 = xlRange.Cells[i, 2].Value2.ToString(); if (dictionary.ContainsKey(col1)) { var existingList = dictionary[col1]; existingList.Add(col2); } else{ var newList = new List<string>(); newList.Add(col2); dictionary.Add(col1, newList); } } //Do whatever you'd like with the dictionary //It now contains this data: A -> [Value1, Value2, Value3], B -> [Value4, Value5] //END OF IMPORTANT SECTION //cleanup GC.Collect(); GC.WaitForPendingFinalizers(); //rule of thumb for releasing com objects: //never use two dots, all COM objects must be referenced and released individually //ex: [somthing].[something].[something] is bad //release com objects to fully kill excel process from running in the background Marshal.ReleaseComObject(xlRange); Marshal.ReleaseComObject(xlWorksheet); //close and release xlWorkbook.Close(); Marshal.ReleaseComObject(xlWorkbook); //quit and release xlApp.Quit(); Marshal.ReleaseComObject(xlApp); } 

注意 :如果您正在处理date,并且使用这些date执行计算对您很重要,那么我将使用DateTime而不是string