所以我想要一个带有2个工作表的Excel文件。 第一个工作表应包含测验中每个用户的得分。 还会有其他信息,例如电子邮件地址或部门。 在第二个工作表中,我想要一个数据透视表,该数据透视表应按部门将“用户计数”分组,以显示用户参与最多的部门的有序列表。
我使用NuGet-Package Epplus,现在有了一个数据透视表,其中包含每个部门的用户总数。但是此列表/表未排序。
public class StatsToExcel
{
public static void ExportToExcelDocument(IEnumerable<QuizUserStatistics> data, HttpContextBase currentContext)
{
ExcelPackage excel = new ExcelPackage();
ExcelWorksheet worksheet = excel.Workbook.Worksheets.Add("Evaluation");
worksheet.Cells[1, 1].LoadFromCollection(data.Select(d => new
{
d.Username,
d.Department,
d.DisplayName,
d.Mail,
d.CorrectAnswers,
d.TotalAnswers
}), true);
worksheet.Cells["A2:F10000"].Sort(5);
var headerList = new List<string>
{
"Username",
"Department",
"Name",
"E-Mail",
"Right Answers",
"Submitted Answers"
};
int index = 1;
foreach (var item in headerList)
{
var cell = worksheet.Cells[1, index++];
cell.Value = item;
cell.Style.Font.Bold = true;
cell.Style.Font.UnderLine = true;
cell.Style.Font.Size = 14f;
}
using (ExcelRange range = worksheet.Cells["D2:D10000"])
{
foreach (ExcelRangeBase x in range)
{
x.Hyperlink = new Uri(x.Value.ToString().Insert(0, "mailto:"));
}
range.Style.Font.UnderLine = true;
range.Style.Font.Color.SetColor(Color.DarkBlue);
}
worksheet.Cells["A2:A10000"].Style.Font.Bold = true;
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
bool printHeaders = true;
var tableStyle = OfficeOpenXml.Table.TableStyles.Medium2;
var dump = excel.Workbook.Worksheets.Add("dump");
using (ExcelRangeBase range = dump.Cells[5, 10]
.LoadFromCollection(data.Select(d => new
{
d.Department
}), printHeaders, tableStyle)) { }
ExcelTable tblData = dump.Tables[dump.Tables.Count - 1];
ExcelPivotTable pivot1 = dump.PivotTables.Add(dump.Cells[8, 12],
dump.Cells[tblData.Address.Address], "groupByDepartmentPivot");
pivot1.ShowHeaders = true;
pivot1.RowHeaderCaption = "Departments";
pivot1.ColumnGrandTotals = true;
pivot1.GrandTotalCaption = "Sum";
pivot1.DataOnRows = false;
pivot1.TableStyle = TableStyles.Medium9;
ExcelPivotTableField DepartmentRowField = pivot1.RowFields.Add(
pivot1.Fields["Department"]
);
ExcelPivotTableDataField departmentDataField = pivot1.DataFields.Add(
pivot1.Fields["Department"]
);
departmentDataField.Function = DataFieldFunctions.Count;
departmentDataField.Name = "Participations by Department";
tblData.Name = "groupByDepartment";
departmentDataField.Field.Sort = eSortType.Descending;
...
}
}
当我对具有给定名称属性“部门参与”的ExcelPivotTableDataField进行排序时,输出中的Excel文件将由具有给定名称属性“部门”的ExcelPivotTableRowField自动排序。 RowField仅包含每个部门的名称,因此它仅按第一行的字母顺序排序。包含DataFields的第二行被跳过。但是,当我在Excel本身中选择一个排序行时,它在下拉列表中同时显示了“部门”和“部门参与”,因此当我选择第二行时,就会得到想要的结果。