导出数据到Excel 2003 单个Sheet页(NPOI)

本文详细介绍了如何使用C#编写代码,将列表数据导出为Excel文件,包括设置工作簿、创建工作表、填充数据以及定义文件名等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  public static void Export<T>(IList<T> sourceData, IList<String> headerList = null, string fileName = null)
        {
            if (sourceData == null)
                throw new ArgumentNullException("sourceData");

            IWorkbook workbook = new HSSFWorkbook();
            var count = 0;
            var sheet = workbook.CreateSheet("Sheet1");

            var properties = TypeDescriptor.GetProperties(typeof(T));
            var row = sheet.CreateRow(0);
            //如果没有自定义的行首,那么采用反射集合的属性名做行首

            var headerCount = headerList != null ? headerList.Count : properties.Count;
            for (var i = 0; i < headerCount; i++) //生成sheet第一行列名 
            {
                var cell = row.CreateCell(count++);
                if (headerList == null)
                {
                    cell.SetCellValue(String.IsNullOrEmpty(properties[i].Description)
                                          ? properties[i].Name
                                          : properties[i].Description);
                }
                else
                    cell.SetCellValue(headerList[i]);
            }

            //将数据导入到excel表中
            for (var i = 0; i < sourceData.Count; i++)
            {
                row = sheet.CreateRow(i + 1);
                count = 0;

                for (var j = 0; j < properties.Count; j++)
                {
                    var cell = row.CreateCell(count++);
                    var value = properties[j].GetValue(sourceData[i]);
                    //日期格式导出修改 huangwei 2013-12-23 yyyy-MM-dd HH:ss
                    //格式应该是"yyyy-MM-dd HH:mm"
                    cell.SetCellValue(value == null ? String.Empty
                        : (value is DateTime ? ((DateTime)value).ToString("yyyy-MM-dd HH:mm") : value.ToString()));
                }
            }

            //定义文件名
            if (string.IsNullOrEmpty(fileName))
                fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            else
                fileName = fileName + ".xls";

            //当前http头信息
            var response = HttpContext.Current.Response;
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
            response.Clear();

            //Write the stream data of workbook to the root directory
            var file = new MemoryStream();
            workbook.Write(file);
            file.WriteTo(response.OutputStream);
            response.End();
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值