欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

npoi2.0将datatable对象转换为excel2007示例

时间:2020-10-28 17:12:31|栏目:.NET代码|点击:

NPOI 2.0将DataTable对象转换为Excel 2007文件提供下载

复制代码 代码如下:

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
        private Stream RenderDataTableToExcel(DataTable SourceTable)
        {
            XSSFWorkbook workbook = null;
            MemoryStream ms = null;
            ISheet sheet = null;
            XSSFRow headerRow = null;
            try
            {
                workbook = new XSSFWorkbook();
                ms = new MemoryStream();
                sheet = workbook.CreateSheet();
                headerRow = (XSSFRow)sheet.CreateRow(0);
                foreach (DataColumn column in SourceTable.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                int rowIndex = 1;
                foreach (DataRow row in SourceTable.Rows)
                {
                    XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
                    foreach (DataColumn column in SourceTable.Columns)
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    ++rowIndex;
                }
                //列宽自适应,只对英文和数字有效
                for (int i = 0; i <= SourceTable.Columns.Count; ++i)
                    sheet.AutoSizeColumn(i);
                workbook.Write(ms);
                ms.Flush();
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                ms.Close();
                sheet = null;
                headerRow = null;
                workbook = null;
            }
            return ms;
        }
        private void DownloadExcel(DataTable dt,string reportName)
        {
                Stream s = RenderDataTableToExcel(dt);
                if (s != null)
                {
                    MemoryStream ms = resultStream.result as MemoryStream;
                    Response.AddHeader("Content-Disposition", string.Format("attachment;filename=" + HttpUtility.UrlEncode(reportName) + DateTime.Now.ToString("yyyyMMdd") + ".xlsx"));
                    Response.AddHeader("Content-Length", ms.ToArray().Length.ToString());
                    Response.BinaryWrite(ms.ToArray());
                    Response.Flush();
                    ms.Close();
                    ms.Dispose();
                }
else
Response.Write("出错,无法下载!");
        }

上一篇:C#中 paint()与Onpaint()的区别

栏    目:.NET代码

下一篇:详解C#中使用对象或集合的初始值设定项初始化的操作

本文标题:npoi2.0将datatable对象转换为excel2007示例

本文地址:http://www.codeinn.net/misctech/16615.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有