ASP.NET MVC5下载数据到Excel文件

项目中的一个功能是将数据导入到Excel文件中,这里使用NPOI操作Excel,代码如下:

public class Excel : IDataTransfer
{
    public Stream Export(string[] titles, List<string>[] dataSource)
    {
        return ExportData(titles, dataSource);
    }

    protected virtual Stream ExportData(string[] titles, List<string>[] dataSource)
    {
        if (dataSource == null)
        {
            throw new ArgumentNullException();
        }
        HSSFWorkbook book = new HSSFWorkbook();
        ISheet sheet = book.CreateSheet("sheet1");
        int rowCount = dataSource.Length;
        int cellCount = dataSource[0].Count;

        var titleRow = sheet.CreateRow(0);
        #region header style
            // 该行的高度
            titleRow.HeightInPoints = 18;
            // 列的样式
            ICellStyle headStyle = book.CreateCellStyle();
            // 单元格内容居中显示
            headStyle.Alignment = HorizontalAlignment.Center;
            // 字体样式
            IFont font = book.CreateFont();
            // 字体大小
            font.FontHeightInPoints = 12;
            // 粗体
            font.Boldweight = 1200;
            // 字体颜色
            font.Color = NPOI.HSSF.Util.HSSFColor.Green.Index;
            headStyle.SetFont(font);
            // 边框
            headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            #endregion

        for (int i = 0; i < titles.Length; i++)
        {
            ICell cell = titleRow.CreateCell(i);
            cell.SetCellValue(titles[i]);
            cell.CellStyle = headStyle;
        }

        for (int i = 0; i < rowCount; i++)
        {
            IRow row = sheet.CreateRow(i + 1);
            for (int j = 0; j < cellCount; j++)
            {
                row.CreateCell(j).SetCellValue(dataSource[i][j]);
            }
        }

        Stream stream = new MemoryStream();
        book.Write(stream);
        book.Close();
        stream.Position = 0;
        return stream;
    }
}

Contorller中的代码:

Excel excel = new Excel();
Stream dataStream = excel.Export(titles.ToArray(), data);
return new FileStreamResult(dataStream, "application/ms-excel") { FileDownloadName = "exportInfo.xlsx" };

 

整个功能的实现并没有太大难度,这里有一点需要注意就是Excel类中的protected virtual Stream ExportData(string[] titles, List<string>[] dataSource)方法,这个方法返回一个流,流中包含要导出的数据。方法的倒数第二行:stream.Position = 0;,这里需要特别注意,将数据写入流中之后,流的位置在最末端,我们要将流的位置重置到起始位置,否则无法读取流中的数据,也就无法导出流中的数据了。

参考文章:

asp.net MVC4.0 将数据 导出 excel 表格
MemoryStream类

版权声明

本文为作者原创,版权归作者雪飞鸿所有。 转载必须保留文章的完整性,且在页面明显位置处标明原文链接

如有问题, 请发送邮件和作者联系。

posted @ 2016-10-10 14:35  雪飞鸿  阅读(3203)  评论(1编辑  收藏  举报