I have created a multidimensional list called Table, which is intended to be exported to an excel sheet. However, when I use the LoadFromCollection method, the resulting excel sheet only displays the following information.
Key Value Item
File System.Collections.Generic.List`1[System.String]
Filter System.Collections.Generic.List`1[System.String]
Date System.Collections.Generic.List`1[System.String]
Actually, each list hast 168 items (making a 169x3 array, including the headers).
Here is the code.
private void button4_Click(object sender, EventArgs e)
{
MultiDimDictList Table = new MultiDimDictList();
Table.Add("File", new List<string>());
Table.Add("Filter", new List<string>());
Table.Add("Date", new List<string>());
// IN THIS PART I POPULATE THE TABLE
ExportToExcel(Table, @"c:\2.xlsx");
}
public void ExportToExcel(MultiDimDictList Matrix, string sourceFiles)
{
FileInfo targetFile = new FileInfo(sourceFiles);
using (var excelFile = new ExcelPackage(targetFile))
{
var worksheet = excelFile.Workbook.Worksheets.Add("Tables");
var range = worksheet.Cells[2, 2];
range.LoadFromCollection(Collection: Matrix, PrintHeaders: true);
excelFile.Save();
}
}
What I'm doing wrong?
I believe in your case it would be much better to use the LoadFromArrays
method.
LoadFromCollection
requires an IEnumerable
of some type. Instead, you're giving it a type with three lists in it.
Using LoadFromArrays
you could do this instead:
IEnumerable<object[]> GetAsEnumerable(MultiDimDictList table)
{
yield return table.Columns.Select(i => (object)i.Name).ToArray();
foreach (var row in table)
{
yield return table.Columns.Select(i => (object)row[i.Name]).ToArray();
}
}
(of course, you have to modify this to suit your MultiDimDictList
type; treat the sample as pseudo-code in where I assume how to load the column list and the row data)
And then just call
range.LoadFromArrays(GetAsEnumerable(Matrix));
Of course, you could also use LoadFromCollection
, it's rather handy. But you'd have to use a different class than MultiDimDictList
for the data. For example, the DataTable
class should do just fine :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.