狠狠色丁香婷婷综合尤物/久久精品综合一区二区三区/中国有色金属学报/国产日韩欧美在线观看 - 国产一区二区三区四区五区tv

LOGO OA教程 ERP教程 模切知識(shí)交流 PMS教程 CRM教程 開(kāi)發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

[點(diǎn)晴永久免費(fèi)OA]【C#】使用NPOI封裝能用于絕大部分場(chǎng)景的導(dǎo)出Execl文件的輔助類

admin
2022年11月25日 15:40 本文熱度 1455
文章簡(jiǎn)介:NPOI生成的文件能和Office編碼一樣,而且創(chuàng)建文件和寫入數(shù)據(jù)很快,這是他的優(yōu)點(diǎn);今天我們分享的是利用NPOI來(lái)封裝一個(gè)適用于大多數(shù)場(chǎng)景的導(dǎo)出輔助類。

分析需求和場(chǎng)景:

    1、一般我們的導(dǎo)出都是在列表頁(yè)面上,列表是分頁(yè)的,導(dǎo)出需要不分頁(yè)導(dǎo)出所有數(shù)據(jù)和列表的所有列;

    2、我們查詢數(shù)據(jù)返回的結(jié)果還不是統(tǒng)一的對(duì)象,比如有時(shí)候是EFCore查詢出來(lái)的List,有時(shí)候是sql直接查詢的DataTable。

    3、數(shù)據(jù)查詢出來(lái)的列順序并不是我們導(dǎo)出的順序,比如查詢出來(lái)ID列在第一個(gè),導(dǎo)出模板是運(yùn)營(yíng)部門定的,他不關(guān)心ID,只關(guān)心Money,要把Money字段放在第一列。也就是說(shuō)我們的導(dǎo)出列是動(dòng)態(tài)靈活的。

     首先說(shuō)下思想,查詢是一樣的,都是用同一個(gè)方法返回?cái)?shù)據(jù)的話,而且要保證想分頁(yè)就分頁(yè),不想分頁(yè)就不分頁(yè),那么:將查詢數(shù)據(jù)的PageSize頁(yè)碼參數(shù)做一個(gè)標(biāo)識(shí),如果PageSize=0,則代表不分頁(yè),底層獲取數(shù)據(jù)的時(shí)候就跳過(guò)分頁(yè)的sql。這樣就解決了同一個(gè)方法供兩個(gè)地方調(diào)用即可分頁(yè)也可不分頁(yè)的難題。

      接下來(lái)就是解決另外兩個(gè)問(wèn)題,第三個(gè)問(wèn)題打算直接在導(dǎo)出生成execl文件的時(shí)候處理,因?yàn)镹POI可以很方便的控制列和生成列,那么第二個(gè)問(wèn)題底層方法返回的數(shù)據(jù)對(duì)象類型不一致,打算采用重載稍微改下應(yīng)該可行。

設(shè)計(jì)思路:

       調(diào)用方直接將導(dǎo)出哪些列用一個(gè)字典的方式傳過(guò)去,輔助類直接根據(jù)字典里面字段順序依次生成列,將數(shù)據(jù)集合反射得到結(jié)果。

直接看代碼:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
namespace C.Customization.Framework
{
    /// <summary>
    /// Npoi輔助類
    /// </summary>
    public class NpoiHepler
    {
        /// <summary>
        /// 實(shí)體類集合導(dǎo)出指定字段到EXCLE
        /// </summary>
        /// <param name="cellHeard">單元頭的Key和Value:{ { "UserName", "姓名" }, { "Age", "年齡" } };</param>
        /// <param name="enList">數(shù)據(jù)源</param>
        /// <param name="sheetName">工作表名稱</param>
        /// <param name="filePath">路徑.xls</param>
        /// <returns>
        /// 文件的下載地址
        /// </returns>
        public static MessageInfo EntitysToExcel(Dictionary<string, string> cellHeard, IList enList, string sheetName, string filePath)
        {
            try
            {
                // 1.檢測(cè)是否存在文件夾,若不存在就建立個(gè)文件夾
                string directoryName = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.createDirectory(directoryName);
                }
                // 2.解析單元格頭部,設(shè)置單元頭的中文名稱
                HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿
                ISheet sheet = workbook.createSheet(sheetName); // 工作表
                IRow row = sheet.createRow(0);
                List<string> keys = cellHeard.Keys.ToList();
                for (int i = 0; i < keys.Count; i++)
                {
                    row.createCell(i).SetCellValue(cellHeard[keys[i]]); // 列名為Key的值
                    sheet.SetColumnWidth(i, 30 * 256);
                }
                // 3.List對(duì)象的值賦值到Excel的單元格里
                int rowIndex = 1; // 從第二行開(kāi)始賦值(第一行已設(shè)置為單元頭)
                foreach (var en in enList)
                {
                    IRow rowTmp = sheet.createRow(rowIndex);
                    for (int i = 0; i < keys.Count; i++) // 根據(jù)指定的屬性名稱,獲取對(duì)象指定屬性的值
                    {
                        string cellValue = ""; // 單元格的值
                        object properotyValue = null; // 屬性的值
                        System.Reflection.PropertyInfo properotyInfo = null; // 屬性的信息
                        // 3.1 若屬性頭的名稱包含'.',就表示是子類里的屬性,那么就要遍歷子類,eg:UserEn.UserName
                        if (keys[i].IndexOf(".") >= 0)
                        {
                            // 3.1.1 解析子類屬性(這里只解析1層子類,多層子類未處理)
                            string[] properotyArray = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                            string subClassName = properotyArray[0]; // '.'前面的為子類的名稱
                            string subClassProperotyName = properotyArray[1]; // '.'后面的為子類的屬性名稱
                            System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 獲取子類的類型
                            if (subClassInfo != null)
                            {
                                // 3.1.2 獲取子類的實(shí)例
                                var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null);
                                // 3.1.3 根據(jù)屬性名稱獲取子類里的屬性類型
                                properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName);
                                if (properotyInfo != null)
                                {
                                    properotyValue = properotyInfo.GetValue(subClassEn, null); // 獲取子類屬性的值
                                }
                            }
                        }
                        else
                        {
                            // 3.2 若不是子類的屬性,直接根據(jù)屬性名稱獲取對(duì)象對(duì)應(yīng)的屬性
                            properotyInfo = en.GetType().GetProperty(keys[i]);
                            if (properotyInfo != null)
                            {
                                properotyValue = properotyInfo.GetValue(en, null);
                            }
                        }
                        // 3.3 屬性值經(jīng)過(guò)轉(zhuǎn)換賦值給單元格值
                        if (properotyValue != null)
                        {
                            cellValue = properotyValue.ToString();
                            // 3.3.1 對(duì)時(shí)間初始值賦值為空
                            if (cellValue.Trim() == "0001/1/1 0:00:00"
                                || cellValue.Trim() == "0001/1/1 23:59:59"
                                || cellValue.Trim() == "1970-01-01 00:00:00")
                            {
                                cellValue = "";
                            }
                        }
                        // 3.4 填充到Excel的單元格里
                        rowTmp.createCell(i).SetCellValue(cellValue);
                    }
                    rowIndex++;
                }
                // 4.生成文件
                FileStream file = new FileStream(filePath, FileMode.create);
                workbook.Write(file);
                file.Close();
                // 5.返回下載路徑
                return new MessageInfo() { IsSucceed = true, Message = filePath };
            }
            catch (Exception ex)
            {
                return new MessageInfo() { IsSucceed = false, Message = ex.Message };
            }
        }
        /// <summary>
        /// 實(shí)體類集合導(dǎo)出指定字段到EXCLE
        /// </summary>
        /// <param name="cellHeard">單元頭的Key和Value:{ { "UserName", "姓名" }, { "Age", "年齡" } };</param>
        /// <param name="enList">數(shù)據(jù)源</param>
        /// <param name="sheetName">工作表名稱</param>
        /// <param name="filePath">路徑.xls</param>
        /// <returns>
        /// 文件的下載地址
        /// </returns>
        public static MessageInfo DataTableToExcel(Dictionary<string, string> cellHeard, DataTable enList, string sheetName, string filePath)
        {
            try
            {
                // 1.檢測(cè)是否存在文件夾,若不存在就建立個(gè)文件夾
                string directoryName = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.createDirectory(directoryName);
                }
                // 2.解析單元格頭部,設(shè)置單元頭的中文名稱
                HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿
                ISheet sheet = workbook.createSheet(sheetName); // 工作表
                IRow row = sheet.createRow(0);
                List<string> keys = cellHeard.Keys.ToList();
                for (int i = 0; i < keys.Count; i++)
                {
                    row.createCell(i).SetCellValue(cellHeard[keys[i]]); // 列名為Key的值
                    sheet.SetColumnWidth(i, 30 * 256);
                }
                // 3.List對(duì)象的值賦值到Excel的單元格里
                int rowIndex = 1; // 從第二行開(kāi)始賦值(第一行已設(shè)置為單元頭)
                for (int en=0;en<enList.Rows.Count;en++)
                {
                    IRow rowTmp = sheet.createRow(rowIndex);
                    for (int i = 0; i < keys.Count; i++) // 根據(jù)指定的屬性名稱,獲取對(duì)象指定屬性的值
                    {
                        string cellValue = ""; // 單元格的值
                        object properotyValue = enList.Rows[en][keys[i]]; // 屬性的值
                        // 3.3 屬性值經(jīng)過(guò)轉(zhuǎn)換賦值給單元格值
                        if (properotyValue != null)
                        {
                            cellValue = properotyValue.ToString();
                            // 3.3.1 對(duì)時(shí)間初始值賦值為空
                            if (cellValue.Trim() == "0001/1/1 0:00:00"
                                || cellValue.Trim() == "0001/1/1 23:59:59"
                                || cellValue.Trim() == "1970-01-01 00:00:00")
                            {
                                cellValue = "";
                            }
                        }
                        // 3.4 填充到Excel的單元格里
                        rowTmp.createCell(i).SetCellValue(cellValue);
                    }
                    rowIndex++;
                }
                // 4.生成文件
                FileStream file = new FileStream(filePath, FileMode.create);
                workbook.Write(file);
                file.Close();
                // 5.返回下載路徑
                return new MessageInfo() { IsSucceed = true, Message = filePath };
            }
            catch (Exception ex)
            {
                return new MessageInfo() { IsSucceed = false, Message = ex.Message };
            }
        }
    }
}

接下來(lái)看調(diào)用方式:當(dāng)返回的是List類型的數(shù)據(jù)時(shí)

       /// <summary>
        /// 導(dǎo)出
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Tb1_Export_Click(object sender, EventArgs e)
        {
            //導(dǎo)出
            List<Mem_MemberInfo> mems = Mem_MemberService.GetInstance().GetListAll();
            Dictionary<string, string> cellHead = new Dictionary<string, string>();
            cellHead[nameof(Mem_MemberInfo.UserName)] = "用戶昵稱";
            cellHead[nameof(Mem_MemberInfo.Mobile)] = "手機(jī)號(hào)";
            cellHead[nameof(Mem_MemberInfo.Balance)] = "余額";
            cellHead[nameof(Mem_MemberInfo.RealName)] = "真實(shí)姓名";
            cellHead[nameof(Mem_MemberInfo.IdCardNum)] = "身份證號(hào)碼";
            cellHead[nameof(Mem_MemberInfo.createTime)] = "注冊(cè)時(shí)間";
            cellHead[nameof(Mem_MemberInfo.Freeze)] = "凍結(jié)金額";
            cellHead[nameof(Mem_MemberInfo.IdentityName)] = "等級(jí)";
            string filename = $"用戶數(shù)據(jù){DateTime.Now:yyyyMMddHHmmss}.xls";
            string filepath = Server.MapPath($"{PageParam.DocumentPath}{filename}");
            MessageInfo msg = NpoiHepler.EntitysToExcel(cellHead, mems, "用戶列表", filepath);
            if (msg.IsSucceed == false)
            {
                Alert.ShowInTop("導(dǎo)出失敗" + msg.Message, MessageBoxIcon.Error);
                return;
            }
            FileInfo file = new FileInfo(msg.Message);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "gb2312");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(filepath);
            Response.Flush();
            Response.End();
        }

這段代碼里面使用的將文件直接按文件流的方式返回,當(dāng)然了,你都得到了導(dǎo)出文件的地址了,用什么方式給前端,都可以。

再看另一種導(dǎo)出DataTable類型的數(shù)據(jù):

        /// <summary>
        /// 導(dǎo)出
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Tb1_Export_Click(object sender, EventArgs e)
        {
            //導(dǎo)出
            PageDataBaseInfo pagedata = FUHelper.GridPageData(Grid1, ttbSearch.Text);
            pagedata.PageSize = 0;
            DataTable dt = Record_WithdrawalService.GetInstance().FindDt(pagedata, "2", RblStatus.selectedValue);
            Dictionary<string, string> cellHead = new Dictionary<string, string>();
            cellHead["SysNo"] = "系統(tǒng)編號(hào)";
            cellHead["Mobile"] = "提現(xiàn)賬戶";
            cellHead["StateName"] = "狀態(tài)";
            cellHead["createTime"] = "申請(qǐng)時(shí)間";
            cellHead["Money"] = "提現(xiàn)金額";
            cellHead["Balance"] = "賬戶余額";
            cellHead["Freeze"] = "凍結(jié)金額";
            cellHead["Remark"] = "備注";
            string filename = $"提現(xiàn)記錄{DateTime.Now:yyyyMMddHHmmss}.xls";
            string filepath = Server.MapPath($"{PageParam.DocumentPath}{filename}");
            MessageInfo msg = NpoiHepler.DataTableToExcel(cellHead, dt, "提現(xiàn)記錄", filepath);
            if (msg.IsSucceed == false)
            {
                Alert.ShowInTop("導(dǎo)出失敗" + msg.Message, MessageBoxIcon.Error);
                return;
            }
            FileInfo file = new FileInfo(msg.Message);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "gb2312");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(filepath);
            Response.Flush();
            Response.End();
        }

注意其中的一句代碼:pagedata.PageSize = 0; 

這就是開(kāi)頭所說(shuō)的利用PageSize來(lái)區(qū)分是否需要分頁(yè)。

到這里就結(jié)束了。


該文章在 2022/11/25 15:40:49 編輯過(guò)
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點(diǎn)晴ERP是一款針對(duì)中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國(guó)內(nèi)大量中小企業(yè)的青睞。
點(diǎn)晴PMS碼頭管理系統(tǒng)主要針對(duì)港口碼頭集裝箱與散貨日常運(yùn)作、調(diào)度、堆場(chǎng)、車隊(duì)、財(cái)務(wù)費(fèi)用、相關(guān)報(bào)表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點(diǎn),圍繞調(diào)度、堆場(chǎng)作業(yè)而開(kāi)發(fā)的。集技術(shù)的先進(jìn)性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點(diǎn)晴WMS倉(cāng)儲(chǔ)管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購(gòu)管理,倉(cāng)儲(chǔ)管理,倉(cāng)庫(kù)管理,保質(zhì)期管理,貨位管理,庫(kù)位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號(hào)管理軟件。
點(diǎn)晴免費(fèi)OA是一款軟件和通用服務(wù)都免費(fèi),不限功能、不限時(shí)間、不限用戶的免費(fèi)OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved