How to add values to a spreadsheet from a dictionary?

帅比萌擦擦* 提交于 2020-01-11 05:43:52

问题


I have a template spreadsheet document that has two columns, Server Name and IP Address. How can I populate the spreadsheet so that each dictionary key goes in its own cell in the Server column and the corresponding value goes in the cell next to it in the IP column?

I am using the EPPlus library but couldn't find anything on the topic.

Below is what I found and tried, but its for lists

using (ExcelPackage package = new ExcelPackage(_fileInfo))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets[1];

    for (int i = 0; i < listOfIPs.Count; i++)
    {
        worksheet.Cells[i + 2, 1].Value = listOfIPs[i];
    }

    package.Save();
}

回答1:


I am not familiar with EPPlus, therefore I am not sure how you get the reference to the active sheet - you need to figure out this bit though once that's done pure C# with a bit of knowledge about VBA model and you can easily avoid any iterations to get contents of your dictionary to a spreadsheet:

// create a sample dictionary and fill it
Dictionary<string, string> myCol = new Dictionary<string, string>();
myCol.Add("server1", "ip1");
myCol.Add("server2", "ip2");

// grab a reference to the active Sheet
// this may vary depending on what framework you are using
Worksheet ws = Globals.ThisWorkbook.ActiveSheet as Worksheet;

// create a Range variable
Range myRange;

// Transpose the keys to column A
myRange = ws.get_Range("A1");
myRange.get_Resize(myCol.Keys.ToArray().Count(),1).Value = 
                 ws.Parent.Parent.Transpose(myCol.Keys.AsEnumerable().ToArray());

// transpose the Values to column B
myRange = ws.get_Range("B1");
myRange.get_Resize(myCol.Values.ToArray().Count(), 1).Value = 
               ws.Parent.Parent.Transpose(myCol.Values.AsEnumerable().ToArray());

Debugging results as expected


With EPPlus I think you can do it like this (untested)

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium);

    package.Save();
}

More details on VBA Collections iterations and printing to Sheet @ vba4all.com




回答2:


You can just access the keys of a dictionary and iterate over them just like you are iterating over the list.

        var foo = new Dictionary<string, string>(); // populate your dictionary
        foreach(var key in foo.Keys)
        {
            var value = foo[key];
            // do stuff with 'key' and 'value', like put them into the excel doc
        }


来源:https://stackoverflow.com/questions/22791116/how-to-add-values-to-a-spreadsheet-from-a-dictionary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!