How to add values to a spreadsheet from a dictionary?

坚强是说给别人听的谎言 提交于 2019-12-01 06:16:23

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

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