update:作业列表导出报错

This commit is contained in:
ltx 2026-07-31 15:44:11 +08:00
parent e049955f9c
commit 1c09b2934f
2 changed files with 43 additions and 7 deletions

View File

@ -89,7 +89,10 @@ namespace VOL.Core.Utilities
}
}
public static byte[] ExportToExcel<T>(Dictionary<string, List<T>> sheetDataList, List<string> fields)
public static byte[] ExportToExcel<T>(
Dictionary<string, List<T>> sheetDataList,
List<string> fields,
bool autoFitColumns = true)
{
using (var package = new ExcelPackage(new FileInfo("filename.xlsx")))
{
@ -101,7 +104,7 @@ namespace VOL.Core.Utilities
var sheetName = sheet.Key;
var worksheet = package.Workbook.Worksheets.Add(sheetName);
ConfigureWorksheet<T>(worksheet, sheetData, fields);
ConfigureWorksheet(worksheet, sheetData, fields, autoFitColumns);
}
return package.GetAsByteArray();
@ -301,7 +304,11 @@ namespace VOL.Core.Utilities
/// <param name="worksheet"></param>
/// <param name="sheetData"></param>
/// <param name="fields"></param>
private static void ConfigureWorksheet<T>(ExcelWorksheet worksheet, IEnumerable<T> sheetData, List<string> fields)
private static void ConfigureWorksheet<T>(
ExcelWorksheet worksheet,
IEnumerable<T> sheetData,
List<string> fields,
bool autoFitColumns)
{
// 添加表头
for (int i = 0; i < fields.Count; i++)
@ -335,8 +342,37 @@ namespace VOL.Core.Utilities
}
}
// 自动调整列宽
worksheet.Cells.AutoFitColumns();
if (autoFitColumns)
{
worksheet.Cells.AutoFitColumns();
return;
}
SetColumnWidthsWithoutGdi(worksheet, fields.Count);
}
private static void SetColumnWidthsWithoutGdi(ExcelWorksheet worksheet, int columnCount)
{
const double minWidth = 10;
const double maxWidth = 40;
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++)
{
var maxContentWidth = worksheet.Cells
.Where(cell => cell.Start.Column == columnIndex)
.Select(cell => GetExcelContentWidth(cell.Value))
.DefaultIfEmpty((int)minWidth)
.Max();
worksheet.Column(columnIndex).Width =
Math.Min(maxWidth, Math.Max(minWidth, maxContentWidth + 2));
}
}
private static int GetExcelContentWidth(object value)
{
var text = value?.ToString() ?? string.Empty;
return text.Sum(character => character > 255 ? 2 : 1);
}
private static string GetDisplayName<T>(string propertyName)
{
@ -749,4 +785,4 @@ namespace VOL.Core.Utilities
return chineseNumbers[tens] + "十" + (units == 0 ? "" : chineseNumbers[units]);
}
}
}
}

View File

@ -77,7 +77,7 @@ namespace VOL.WebApi.Controllers.Business
nameof(HomeWorkStudentExportModel.Result)
};
var excelBytes = Tool.ExportToExcel(sheets, columns);
var excelBytes = Tool.ExportToExcel(sheets, columns, autoFitColumns: false);
var fileName = $"作业学生明细{DateTime.Now:yyyyMMddHHmmss}.xlsx";
return File(
excelBytes,