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

Serwa ·
更新时间:2024-11-13
· 792 次阅读

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();
    &n bsp;           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#使用NPOI导入Excel的方法详解c# 应用NPOI获取Excel中的图片,保存至本地的算法C#通过NPOI操作Excel的实例代码详解免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)C#基于NPOI生成具有精确列宽行高的Excel文件的方法Asp.Net使用Npoi导入导出Excel的方法asp.net使用npoi读取excel模板并导出下载详解用NPOI创建Excel、合并单元格、设置单元格样式、边框的方法使用Npoi操作excel的解决办法C#使用NPOI上传excel



npoi 示例 datatable

需要 登录 后方可回复, 如果你还没有账号请 注册新账号