c# Datatable導出Excel

来源:https://www.cnblogs.com/yuanzijian-ruiec/archive/2018/10/01/9734280.html
-Advertisement-
Play Games

using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.L... ...


using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
namespace EasyFrame.Common
{
    /// <summary>
    ///title調用信息
    /// </summary>
    public class ChartTitle
    {
        /// <summary>
        /// 調用名
        /// </summary>
        public string CallName { get; set; }
        /// <summary>
        /// 標頭信息
        /// </summary>
        public List<ChartName> SetNameList { get; set; }
    }
    public class ChartName
    {
        /// <summary>
        /// 一級標頭
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 二級標頭
        /// </summary>
        public List<string> ChartChildNameList { get; set; }

    }

    public class ExcelHelper
    {

        //
        /// <summary>
        /// Datatable導出Excel
        /// </summary>
        /// <param name="dt">數據</param>
        /// <param name="list">表頭</param>
        /// <param name="counts">總條數</param>
        /// <param name="filePath">保存地址</param>
        /// <returns></returns>
        public static MemoryStream WriteExcel(DataTable dt, List<ChartTitle> objlist, string filePath)
        {
            var list = objlist.FirstOrDefault(a => a.CallName == "ccc").SetNameList;
            if (!string.IsNullOrEmpty(filePath) && null != dt && dt.Rows.Count > 0)
            {
                XSSFWorkbook book = new XSSFWorkbook();
                NPOI.SS.UserModel.ISheet sheet = book.CreateSheet(dt.TableName);
                ICell cell = null;
                ICellStyle style = book.CreateCellStyle();
                IFont font = book.CreateFont();//創建字體樣式  
                IFont fonts = book.CreateFont();//創建字體樣式  
                IFont fontss = book.CreateFont();//創建字體樣式  
                font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;//設置字體顏色
                ICellStyle styles = book.CreateCellStyle(); //紅色
                fonts.Color = NPOI.HSSF.Util.HSSFColor.Green.Index;
                ICellStyle styless = book.CreateCellStyle(); //綠色
                fontss.Color = NPOI.HSSF.Util.HSSFColor.Blue.Index;
                ICellStyle stylesss = book.CreateCellStyle(); //藍色
                styless.SetFont(fonts);
                styles.SetFont(font);
                stylesss.SetFont(fontss);
                style.Alignment = HorizontalAlignment.Center;
                NPOI.SS.UserModel.IRow row1 = sheet.CreateRow(0);
                NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(1);
                var row = row1;
                int num = 0;//記錄列
                var d = true;//是否第一次載入到二級表單
                #region  創建表頭
                //兩行單列
                for (int i = 0; i < list.Count; i++)
                {
                    if (!d)
                    {
                        row = row1;
                        d = true;
                    }
                    if (list[i].ChartChildNameList == null)
                    {
                        cell = row.CreateCell(num);
                        sheet.SetColumnWidth(num, 15 * 256);
                        cell.SetCellValue(list[i].Name);
                        cell.CellStyle = style;
                        sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 1, num, num));
                        num++;
                        continue;
                    }
                    //兩行多列
                    var count = list[i].ChartChildNameList.Count; //列數
                    cell = row.CreateCell(num);
                    cell.SetCellValue(list[i].Name);
                    cell.CellStyle = style;
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, num, count + num - 1));
                    if (d)
                    {
                        d = false;
                        row = row2;
                    }
                    var t = 0;
                    var rang = sheet.GetRow(1);
                    for (int j = 0; j < count; j++)
                    {
                        sheet.SetColumnWidth(num + t, 5 * 256);
                        cell = row.CreateCell(num + t);
                        cell.SetCellValue(list[i].ChartChildNameList[j]);
                        cell.CellStyle = style;
                        t++;
                    }
                    num = num + count;
                }
                #endregion 創建表頭
                #region 寫入數據
                int customs = 0;//記錄列數
                int clouns = 0;//記錄行數



                filePath = string.Format(filePath, "XXX");
                #region 導出操作
                var data1 = JsonConvert.DeserializeObject<List<類名>>(dt.Rows[0][0].ToString());
                foreach (var item in data1)
                {
                    NPOI.SS.UserModel.IRow rows = sheet.CreateRow(clouns + 2);
                    customs = 0;
                    rows.CreateCell(customs).SetCellValue(Convert.ToString(item.No)); customs++;
                    rows.CreateCell(customs).SetCellValue(Convert.ToString(item.LotteryOpenNo)); customs++;
                    for (int i = 0; i < item.Wan.Length; i++)
                    {
                        if (item.LotteryOpenNo.Split(',')[0] == item.Wan[i].ToString())
                        {
                            cell = rows.CreateCell(customs);
                            cell.SetCellValue(item.Wan[i]);
                            cell.CellStyle = styles;
                            customs++;
                        }
                        else
                        {
                            rows.CreateCell(customs).SetCellValue(item.Wan[i]); customs++;
                        }
                    }
                    for (int j = 0; j < item.Qian.Length; j++)
                    {
                        if (item.LotteryOpenNo.Split(',')[1] == item.Qian[j].ToString())
                        {
                            cell = rows.CreateCell(customs);
                            cell.SetCellValue(item.Qian[j]);
                            cell.CellStyle = styles;
                            customs++;
                        }
                        else
                        {
                            rows.CreateCell(customs).SetCellValue(item.Qian[j]); customs++;
                        }
                    }
                    for (int k = 0; k < item.Bai.Length; k++)
                    {
                        if (item.LotteryOpenNo.Split(',')[2] == item.Bai[k].ToString())
                        {
                            cell = rows.CreateCell(customs);
                            cell.SetCellValue(item.Bai[k]);
                            cell.CellStyle = styles;
                            customs++;
                        }
                        else
                        {
                            rows.CreateCell(customs).SetCellValue(item.Bai[k]); customs++;
                        }
                    }
                    for (int l = 0; l < item.Shi.Length; l++)
                    {
                        if (item.LotteryOpenNo.Split(',')[3] == (item.Shi[l].ToString()))
                        {
                            cell = rows.CreateCell(customs);
                            cell.SetCellValue(item.Shi[l]);
                            cell.CellStyle = styles;
                            customs++;
                        }
                        else
                        {
                            rows.CreateCell(customs).SetCellValue(item.Shi[l]); customs++;
                        }
                    }
                    for (int m = 0; m < item.Ge.Length; m++)
                    {
                        if (item.LotteryOpenNo.Split(',')[4] == (item.Ge[m].ToString()))
                        {
                            cell = rows.CreateCell(customs);
                            cell.SetCellValue(item.Ge[m]);
                            cell.CellStyle = styles;
                            customs++;
                        }
                        else
                        {
                            rows.CreateCell(customs).SetCellValue(item.Ge[m]); customs++;
                        }
                    }
                    for (int n = 0; n < item.Fen.Length; n++)
                    {
                        if (item.LotteryOpenNo.Contains(item.Fen[n].ToString()))
                        {
                            cell = rows.CreateCell(customs);
                            cell.SetCellValue(item.Fen[n]);
                            cell.CellStyle = styles;
                            customs++;
                        }
                        else
                        {
                            rows.CreateCell(customs).SetCellValue(item.Fen[n]); customs++;
                        }

                    }
                    clouns++;
                }

                #endregion


                #endregion 寫入數據
                // 寫入到客戶端  
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    book.Write(ms);
                    using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                    book = null;
                    return ms;
                }
            }
            return null;
        }



    }
}

 


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

-Advertisement-
Play Games
更多相關文章
  • django商城項目基本配置,1.pycharm相關配置.2.調整工程的目錄結構.3.項目導包路徑,4.資料庫與redis配置。5.日誌與異常配置 ...
  • 導航: 1、創建進程的兩種方式2、Process的方法3、進程間的通訊1,進程隊列Queue--先進先出4、進程間的通訊2,管道通訊 Pipe5、進程間的數據共用,Manager6、多進程同步問題7、進程池Pool python中多進程可以解決cpython解釋器多線程中GIL存在的問題,可以利用C ...
  • Dapper作為.NET生態中廣為人知的輕量級ORM類庫在.NET Core里仍能被有效利用,並且其不但可以連通SQL Server資料庫還提供對其它資料庫,比如MySQL的支持。這裡試驗了一下通過Dapper連接MySQL的方法。 MySQL 可以選擇直接安裝在原生系統中或是Docker里。 "O ...
  • 一、 新建一個Winform項目 二、使用Nuget添加引用 安裝下圖中紅色框住的兩個程式包 安裝完後發現安裝瞭如下圖的程式包,這是因為上述兩個程式包存在對其它程式包的依賴。 三、編寫程式 1. 窗體設計,攝像頭是下拉列表(cmbCamera,控制項命名,下同),雖然示例只用到一個攝像頭,但是該Dem ...
  • /// /// 生成驗證碼圖片 /// /// public byte[] GetVerifyCode() { int codeW = 80; int codeH = 40; int fontSize = 18; ... ...
  • /// /// 對Url進行編碼 /// /// url /// 編碼字元是否轉成大寫,範例,"http://"轉成"http%3A%2F%2F" public static string UrlEncode(string url, bool isUpper = false) { ... ...
  • using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using Sy... ...
  • using System; using System.Collections.Generic; using System.Text; using System.Configuration; using System.IO; using System.Web; using System.Net.Mai... ...
一周排行
    -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.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...