程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> npoi2.0將datatable對象轉換為excel2007示例

npoi2.0將datatable對象轉換為excel2007示例

編輯:C#入門知識

npoi2.0將datatable對象轉換為excel2007示例。本站提示廣大學習愛好者:(npoi2.0將datatable對象轉換為excel2007示例)文章只能為提供參考,不一定能成為您想要的結果。以下是npoi2.0將datatable對象轉換為excel2007示例正文


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("失足,沒法下載!");
        }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved