从C#中的excel数据创建HashMap

时间:2016-10-18 13:20:28

标签: c# excel hashmap

我是C#的新手,我有一个包含2列的Excel工作表,我想在该工作表中的日期之外创建一个hashmap。让excel表看起来像

 A         Value1
 A         Value2
 A         Value3
 B         value4
 B         value5

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

我想创建一个类似

的散列图
HashMap<String, List<String>>();

String将成为键,List将是该键的值

有什么想法吗?

谢谢

1 个答案:

答案 0 :(得分:1)

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

查看我如何使用Dictionary代替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);
}

注意:如果您正在处理日期并使用这些日期执行计算对您很重要,我会使用DateTime代替string