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;,这里需要特别注意,将数据写入流中之后,流的位置在最末端,我们要将流的位置重置到起始位置,否则无法读取流中的数据,也就无法导出流中的数据了。

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值