tt
public static byte[] ConvertDataTableToExcelBuffer(DataTable table) { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; byte[] result = null; using (var ms = new MemoryStream()) { using (ExcelPackage package = new ExcelPackage(ms)) { // add a new worksheet to the empty workbook ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Documents"); //First add the headers int colIndex = 1; foreach (DataColumn prop in table.Columns) { worksheet.Cells[1, colIndex].Value = prop.ColumnName; colIndex++; } var row = 2; foreach (DataRow doc in table.Rows) { colIndex = 1; foreach (DataColumn prop in table.Columns) { var value = doc[prop.ColumnName]; if (value != null) { value = value.ToString().Replace("<br>", ""); } worksheet.Cells[$"{GetExcelColumnName(colIndex)}{row}"].Value = value; colIndex++; } row++; } package.Save(); //Save the workbook. ms.Position = 0; //var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //var fileName = $"doc_exp_{DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")}.xlsx"; } result = ms.ToArray(); } return result; }
var filebyte = ExcelHelper.ConvertToExcelBuffer(ds);
var fname = $"{t}-{DateTime.Now.ToString("yyyyMMddHHmmss")}";
return this.File(filebyte, "application/octet-stream", fname + ".xlsx");
private static string GetExcelColumnName(int columnNumber)
{
int dividend = columnNumber;
string columnName = String.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName;
}