将DataTable 变成byte 传给前台下载

时间:2021-04-07
本文章向大家介绍将DataTable 变成byte 传给前台下载,主要包括将DataTable 变成byte 传给前台下载使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

public static byte[] ToExcelBytes(this DataTable dt, string sheetName = "Sheet1")
{
if (dt == null)
{
return null;
}

        HSSFWorkbook hSSFWorkbook = new HSSFWorkbook();
        ISheet sheet = hSSFWorkbook.CreateSheet(sheetName);
        IRow row = sheet.CreateRow(0);
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            string text = dt.Columns[i].Caption;
            if (string.IsNullOrWhiteSpace(text))
            {
                text = dt.Columns[i].ColumnName;
            }

            row.CreateCell(i).SetCellValue(text);
        }

        for (int j = 0; j < dt.Rows.Count; j++)
        {
            IRow row2 = sheet.CreateRow(j + 1);
            for (int k = 0; k < dt.Columns.Count; k++)
            {
                row2.CreateCell(k).SetCellValue(dt.Rows[j][k].ToString());
            }
        }

        using (MemoryStream memoryStream = new MemoryStream())
        {
            hSSFWorkbook.Write(memoryStream);
            memoryStream.Flush();
            return memoryStream.GetBuffer();
        }
    }

原文地址:https://www.cnblogs.com/issac-9608/p/14629356.html