在C#中将字典写入Excel

我有一个string作为关键字和string列表作为值的字典。 我想将值写入Excel,以便键位于最上面一行,并且它们的值位于相应的列中。 我已经有一些代码将写入到顶部行的键,但我不知道如何做的价值观。 提前致谢!

Excel.Application oXL = new Excel.Application(); Excel._Workbook oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value)); Excel._Worksheet oSheet = (Excel._Worksheet)oWB.ActiveSheet; Excel.Range oRng; string[] saNames = dict.Keys.ToArray(); oRng = oSheet.get_Range("A1", Missing.Value).get_Resize(1, dict.Keys.Count); oRng.Value = saNames; oXL.Visible = true; oXL.UserControl = true; 

像这样的东西? 浏览每个键,把它写在最上面一行,然后在连续键的值中查看string。

 int column = 1; // Initialize for keys. foreach (string key in dict.Keys) { int row = 1; // Initialize for values in key. oSheet.Cells(row, column).Value = key; foreach (string value in dict[key]) { row++; oSheet.Cells(row,column).Value = value; } column++; // increment for next key. } 

我知道不是EXCEL,但是如果CSV格式对你来说足够好的话,那么这里就是一个适合我的例子。 当然使用SystemSystem.IOSystem.Linq

  public static void DictToCsv(Dictionary<string, string> dict, string filePath) { try { var csvLines = String.Join(Environment.NewLine, dict.Select(d => d.Key + "," + d.Value)); Directory.CreateDirectory(Path.GetDirectoryName(filePath)) File.WriteAllText(filePath, csvLines); } catch (Exception ex) { logger.Error(ex.ToString()); } } 

请享用