NPOI操作Excel文件

来源:http://www.cnblogs.com/ucos/archive/2017/04/28/6781475.html
-Advertisement-
Play Games

首先,通過NuGet添加NPOI. NPOI依賴SharpZipLib,通過NuGet添加SharpZipLib. 然後添加NPOI. 添加後項目的引用列表如下: 把DataTable轉換成Excel文件。 代碼如下: public static MemoryStream RenderDataTab ...


首先,通過NuGet添加NPOI. 

NPOI依賴SharpZipLib,通過NuGet添加SharpZipLib.

然後添加NPOI.

 

添加後項目的引用列表如下:

 

把DataTable轉換成Excel文件。

代碼如下: 

        public static MemoryStream RenderDataTableToExcel(DataTable table)
        {
            MemoryStream ms = new MemoryStream();

            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet(table.TableName);

            for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in table.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(table.Rows[rowIndex][column].ToString());
                }
            }

            workbook.Write(ms);
            ms.Close();

            return ms;
        }
View Code

轉換Excel文件內容如下:

 

Excel文件添加表頭

代碼: 

        public static MemoryStream RenderDataTableToExcelWithHeader(DataTable table)
        {
            MemoryStream ms = new MemoryStream();

            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet(table.TableName);
            IRow headerRow = sheet.CreateRow(0);
            foreach (DataColumn column in table.Columns)
            {
                headerRow.CreateCell(column.Ordinal).SetCellValue(string.Format("    {0}    ", column.Caption));
            }

            for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
            {
                IRow dataRow = sheet.CreateRow(rowIndex+1);
                foreach (DataColumn column in table.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(table.Rows[rowIndex][column].ToString());
                }
            }

            workbook.Write(ms);
            ms.Close();

            return ms;
        }
View Code

轉換Excel文件內容如下:

 

添加Excel文件添加表頭樣式

 代碼: 

public static MemoryStream RenderDataTableToExcelWithHeaderRowStyle(DataTable table)
        {
            MemoryStream ms = new MemoryStream();

            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet(table.TableName);
            IRow headerRow = sheet.CreateRow(0);

            ICellStyle headStyle = workbook.CreateCellStyle();
            headStyle.Alignment = HorizontalAlignment.Center;
            headStyle.FillForegroundColor = HSSFColor.Grey25Percent.Index;
            headStyle.FillPattern = FillPattern.SolidForeground;
            IFont font = workbook.CreateFont();
            font.FontName = "Microsoft Yahei";
            font.FontHeightInPoints = 11;
            font.IsBold = true;
            font.Color = HSSFColor.White.Index;
            headStyle.SetFont(font);
            headStyle.BorderBottom = BorderStyle.Thin;
            headStyle.BorderRight = BorderStyle.Thin;
            headStyle.BorderLeft = BorderStyle.Thin;

            foreach (DataColumn column in table.Columns)
            {
                ICell cell = headerRow.CreateCell(column.Ordinal);
                cell.SetCellValue(string.Format("    {0}    ", column.Caption));
                cell.CellStyle = headStyle;
            }

            for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
            {
                IRow dataRow = sheet.CreateRow(rowIndex + 1);
                foreach (DataColumn column in table.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(table.Rows[rowIndex][column].ToString());
                }
            }

            workbook.Write(ms);
            ms.Close();

            return ms;
        }
View Code

轉換Excel文件內容如下:

 

添加Excel文件添加數據行樣式

  代碼: 

public static MemoryStream RenderDataTableToExcelWithDataRowStyle(DataTable table)
        {
            MemoryStream ms = new MemoryStream();

            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet(table.TableName);
            IRow headerRow = sheet.CreateRow(0);

            ICellStyle headStyle = workbook.CreateCellStyle();
            headStyle.Alignment = HorizontalAlignment.Center;
            headStyle.FillForegroundColor = HSSFColor.Grey25Percent.Index;
            headStyle.FillPattern = FillPattern.SolidForeground;
            IFont font = workbook.CreateFont();
            font.FontName = "Microsoft Yahei";
            font.FontHeightInPoints = 11;
            font.IsBold = true;
            font.Color = HSSFColor.White.Index;
            headStyle.SetFont(font);
            headStyle.BorderBottom = BorderStyle.Thin;
            headStyle.BorderRight = BorderStyle.Thin;
            headStyle.BorderLeft = BorderStyle.Thin;

            ICellStyle dataRowEvenStyle = workbook.CreateCellStyle();
            dataRowEvenStyle.Alignment = HorizontalAlignment.Center;
            dataRowEvenStyle.FillForegroundColor = HSSFColor.LightOrange.Index;
            dataRowEvenStyle.FillPattern = FillPattern.SolidForeground;
            IFont dataRowEvenFont = workbook.CreateFont();
            dataRowEvenFont.FontName = "Microsoft Yahei";
            dataRowEvenFont.FontHeightInPoints = 11;
            dataRowEvenFont.Color = HSSFColor.Blue.Index;
            dataRowEvenStyle.SetFont(dataRowEvenFont);
            dataRowEvenStyle.BorderBottom = BorderStyle.Thin;
            dataRowEvenStyle.BorderRight = BorderStyle.Thin;
            dataRowEvenStyle.BorderLeft = BorderStyle.Thin;

            ICellStyle dataRowOddStyle = workbook.CreateCellStyle();
            dataRowOddStyle.Alignment = HorizontalAlignment.Center;
            dataRowOddStyle.FillForegroundColor = HSSFColor.LightGreen.Index;
            dataRowOddStyle.FillPattern = FillPattern.SolidForeground;
            IFont dataRowOddFont = workbook.CreateFont();
            dataRowOddFont.FontName = "Microsoft Yahei";
            dataRowOddFont.FontHeightInPoints = 11;
            dataRowOddFont.Color = HSSFColor.Black.Index;
            dataRowOddStyle.SetFont(dataRowOddFont);
            dataRowOddStyle.BorderBottom = BorderStyle.Thin;
            dataRowOddStyle.BorderRight = BorderStyle.Thin;
            dataRowOddStyle.BorderLeft = BorderStyle.Thin;

            foreach (DataColumn column in table.Columns)
            {
                ICell cell = headerRow.CreateCell(column.Ordinal);
                cell.SetCellValue(string.Format("    {0}    ", column.Caption));
                cell.CellStyle = headStyle;
            }

            for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
            {
                IRow dataRow = sheet.CreateRow(rowIndex + 1);
                foreach (DataColumn column in table.Columns)
                {
                    ICell cell = dataRow.CreateCell(column.Ordinal);
                    cell.SetCellValue(table.Rows[rowIndex][column].ToString());
                    if (rowIndex % 2 == 0)
                    {
                        cell.CellStyle = dataRowEvenStyle;
                    }
                    else
                    {
                        cell.CellStyle = dataRowOddStyle;
                    }
                }
            }

            workbook.Write(ms);
            ms.Close();

            return ms;
        }
View Code

轉換Excel文件內容如下:

Excel文件合併單元格

代碼: 

public static MemoryStream RenderDataTableToExcelMergedRegion(DataTable table)
        {
            MemoryStream ms = new MemoryStream();

            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet(table.TableName);
            IRow headerRow = sheet.CreateRow(0);

            ICellStyle headStyle = workbook.CreateCellStyle();
            headStyle.Alignment = HorizontalAlignment.Center;
            headStyle.FillForegroundColor = HSSFColor.Grey25Percent.Index;
            headStyle.FillPattern = FillPattern.SolidForeground;
            IFont font = workbook.CreateFont();
            font.FontName = "Microsoft Yahei";
            font.FontHeightInPoints = 11;
            font.IsBold = true;
            font.Color = HSSFColor.White.Index;
            headStyle.SetFont(font);
            headStyle.BorderBottom = BorderStyle.Thin;
            headStyle.BorderRight = BorderStyle.Thin;
            headStyle.BorderLeft = BorderStyle.Thin;

            ICellStyle dataRowEvenStyle = workbook.CreateCellStyle();
            dataRowEvenStyle.Alignment = HorizontalAlignment.Center;
            dataRowEvenStyle.FillForegroundColor = HSSFColor.LightOrange.Index;
            dataRowEvenStyle.FillPattern = FillPattern.SolidForeground;
            IFont dataRowEvenFont = workbook.CreateFont();
            dataRowEvenFont.FontName = "Microsoft Yahei";
            dataRowEvenFont.FontHeightInPoints = 11;
            dataRowEvenFont.Color = HSSFColor.Blue.Index;
            dataRowEvenStyle.SetFont(dataRowEvenFont);
            dataRowEvenStyle.BorderBottom = BorderStyle.Thin;
            dataRowEvenStyle.BorderRight = BorderStyle.Thin;
            dataRowEvenStyle.BorderLeft = BorderStyle.Thin;

            ICellStyle dataRowOddStyle = workbook.CreateCellStyle();
            dataRowOddStyle.Alignment = HorizontalAlignment.Center;
            dataRowOddStyle.FillForegroundColor = HSSFColor.LightGreen.Index;
            dataRowOddStyle.FillPattern = FillPattern.SolidForeground;
            IFont dataRowOddFont = workbook.CreateFont();
            dataRowOddFont.FontName = "Microsoft Yahei";
            dataRowOddFont.FontHeightInPoints = 11;
            dataRowOddFont.Color = HSSFColor.Black.Index;
            dataRowOddStyle.SetFont(dataRowOddFont);
            dataRowOddStyle.BorderBottom = BorderStyle.Thin;
            dataRowOddStyle.BorderRight = BorderStyle.Thin;
            dataRowOddStyle.BorderLeft = BorderStyle.Thin;

            foreach (DataColumn column in table.Columns)
            {
                ICell cell = headerRow.CreateCell(column.Ordinal);
                cell.SetCellValue(string.Format("    {0}    ", column.Caption));
                cell.CellStyle = headStyle;
            }

            for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
            {
                IRow dataRow = sheet.CreateRow(rowIndex + 1);
                foreach (DataColumn column in table.Columns)
                {
                    ICell cell = dataRow.CreateCell(column.Ordinal);
                    cell.SetCellValue(table.Rows[rowIndex][column].ToString());
                    if (rowIndex % 2 == 0)
                    {
                        cell.CellStyle = dataRowEvenStyle;
                    }
                    else
                    {
                        cell.CellStyle = dataRowOddStyle;
                    }
                }
            }

            sheet.AddMergedRegion(new CellRangeAddress(1, 2, 0, 0));
            sheet.AddMergedRegion(new CellRangeAddress(3, 4, 0, 0));
            sheet.AddMergedRegion(new CellRangeAddress(5, 6, 0, 0));
            sheet.AddMergedRegion(new CellRangeAddress(7, 8, 0, 0));
            sheet.AddMergedRegion(new CellRangeAddress(9, 10, 0, 0));

            workbook.Write(ms);
            ms.Close();

            return ms;
        }
View Code

轉換Excel文件內容如下:

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 從編程的角度來講,ASP.NET Web API針對CORS的實現僅僅涉及到HttpConfiguration的擴展方法EnableCors和EnableCorsAttribute特性。但是整個CORS體系不限於此,在它們背後隱藏著一系列的類型,我們將會利用本章餘下的內容對此作全面講述,今天我們就來 ...
  • 為什麼要使用StringBuilder 為什麼要使用StringBuilder 為什麼要使用StringBuilder 為什麼使用StringBuilder要從string對象的特性說起。 為什麼使用StringBuilder要從string對象的特性說起。 string對象在進行字元串拼接時,因為 ...
  • 簡介 簡介 對於.net來說,用web api來構建服務是一個不錯的選擇,都是http請求,調用簡單,但是如果真的要在程式中調用,則還有些工作要做,比如我們需要手寫httpClient調用,並映射Model, 如果服務少還可以,多了就繁瑣了。 Swagger Swagger 關於Swagger的信息 ...
  • 我們在上面對ASP.NET Core預設提供的具有跨平臺能力的KestrelServer進行了詳細介紹(《聊聊ASP.NET Core預設提供的這個跨平臺的伺服器——KestrelServer》),為了讓讀者朋友們對管道中的Server具有更加深刻的認識,接下來我們採用實例演示的形式創建一個自定義的 ...
  • 概述: ASP.NET Web API 的好用使用過的都知道,沒有複雜的配置文件,一個簡單的ApiController加上需要的Action就能工作。但是在使用API的時候總會遇到跨域請求的問題, 特別各種APP萬花齊放的今天,對API使用者身份角色驗證是不能避免的(完全開發的API不需要對使用者身 ...
  • 本節所謂的“配置同步”主要體現在兩個方面:其一,如何監控配置源併在其變化的時候自動載入其數據,其目的是讓應用中通過Configuration對象承載的配置與配置源的數據同步;其二、當Configuration對象承載的配置放生變換的時候如何嚮應用程式發送通知,最終讓應用程式使用最新的配置。 一、配置 ...
  • 本系列英文原文出自。 提示1. 在Entity Framework中怎樣排序關係(Relationships) 問題: 在Entity Framework論壇中常會看到關於排序相關聯項目的問題。 例如,想象你要查詢客戶,並返回那些欠款超過30的賬戶,與此同時檢索這些賬戶的訂單。 並且你需要將那些訂單 ...
  • 平時我們在用多線程開發的時候少不了Task,確實task給我們帶來了巨大的編程效率,在Task底層有一個TaskScheduler,它決定了task該如何被調度,而 在.net framework中有兩種系統定義Scheduler,第一個是Task預設的ThreadPoolTaskScheduler ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...