NETCORE API NPOI導出功能+Vue下載(二)

需求:前后端完全分離的項目,需要一個導出功能,前端使用ant design vue,后端 NetCore5.0

API導出功能:

        /// <summary>
        /// 導出
        /// </summary>
        /// <param name="input">篩選條件</param>
        /// <returns></returns>
        [HttpGet("/ActiveManage/exportExcel")]
        public async Task<IActionResult> ExcelDataExprot([FromQuery] ActiveManageInputBySearch input) {
            
           //ExcelActive 類名 根據(jù)不同實體進行導出
          //參數(shù)活動管理,導出excel名稱和sheet名稱
          // 參數(shù)entities  List<ExcelActive >
          // 參數(shù)title  excel 標題
           return await NPOIHelper<ExcelActive>.ExcelDataExprot("活動管理", entities,title);
            
        }
image.png

NPOI導出公共類:

namespace Furion.Extras.Admin.NET.Application
{
    public class  NPOIHelper<T> where T:class
    {
        public static async Task<IActionResult> ExcelDataExprot(string tablename,List<T> list,List<string> ExcelTitle) {

            try {
            //創(chuàng)建Excel文件對象
            var workbook = new HSSFWorkbook();
            //創(chuàng)建工作表sheet0
            var sheet = workbook.CreateSheet(tablename);
            //設(shè)置頂部大標題樣式
            var TitleCellStyleFont = NpoiExcelExportHelper._.CreateStyle(workbook,HorizontalAlignment.Center,VerticalAlignment.Center,20,true,700,"楷體", true, false, false, true, FillPattern.SolidForeground, HSSFColor.Coral.Index, HSSFColor.White.Index,
                    FontUnderlineType.None, FontSuperScript.None, false);
            //第一行表單
            var row = NpoiExcelExportHelper._.CreateRow(sheet, 0, 28);
            var cell = row.CreateCell(0);
            //合并單元格 例: 第1行到第2行 第3列到第4列圍成的矩形區(qū)域
            //TODO:關(guān)于Excel行列單元格合并問題
            /**
              第一個參數(shù):從第幾行開始合并
              第二個參數(shù):到第幾行結(jié)束合并
              第三個參數(shù):從第幾列開始合并
              第四個參數(shù):到第幾列結(jié)束合并
            **/
            CellRangeAddress region = new CellRangeAddress(0, 0, 0, ExcelTitle.Count()-1);
            sheet.AddMergedRegion(region);
            cell.SetCellValue(tablename);//合并單元格后,只需對第一個位置賦值即可(TODO:頂部標題)
            cell.CellStyle = TitleCellStyleFont;
            //二級標題列樣式設(shè)置
            var headTopStyle = NpoiExcelExportHelper._.CreateStyle(workbook, HorizontalAlignment.Center, VerticalAlignment.Center, 15, true, 700, "楷體", true, false, false, true, FillPattern.SolidForeground, HSSFColor.Grey25Percent.Index, HSSFColor.Black.Index,
            FontUnderlineType.None, FontSuperScript.None, false);
                //表頭名稱
                var headerName = list[0];

                row = NpoiExcelExportHelper._.CreateRow(sheet, 1, 24);//第二行
                for(int i=0;i< ExcelTitle.Count;i++) { 
             
                cell = NpoiExcelExportHelper._.CreateCells(row, headTopStyle, i, ExcelTitle[i]);
                    
                    //設(shè)置單元格寬度
                 sheet.SetColumnWidth(i, 7000);

                }

            #region 單元格內(nèi)容信息

            //單元格邊框樣式
            var cellStyle = NpoiExcelExportHelper._.CreateStyle(workbook, HorizontalAlignment.Center, VerticalAlignment.Center, 10, true, 400);

            //左側(cè)列單元格合并 begin
            //TODO:關(guān)于Excel行列單元格合并問題(合并單元格后,只需對第一個位置賦值即可)
            /**
              第一個參數(shù):從第幾行開始合并
              第二個參數(shù):到第幾行結(jié)束合并
              第三個參數(shù):從第幾列開始合并
              第四個參數(shù):到第幾列結(jié)束合并
            **/
         
            for (var i = 0; i < list.Count(); i++)
            {
                    row = NpoiExcelExportHelper._.CreateRow(sheet, i + 2, 20); //sheet.CreateRow(i+2);//在上面表頭的基礎(chǔ)上創(chuàng)建行
                    int y = 0;
                    foreach (System.Reflection.PropertyInfo p in list[i].GetType().GetProperties())
                    {
                        cell = NpoiExcelExportHelper._.CreateCells(row, cellStyle, y, p.GetValue(list[i]) != null ? p.GetValue(list[i]).ToString() : null);
                        y++;
                    }
            }
                #endregion

                //excel保存文件名
                string excelFileName = tablename + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                //將Excel表格轉(zhuǎn)化為流,輸出

                MemoryStream bookStream = new MemoryStream();//創(chuàng)建文件流

                workbook.Write(bookStream); //文件寫入流(向流中寫入字節(jié)序列)

                bookStream.Seek(0, SeekOrigin.Begin);//輸出之前調(diào)用Seek,把0位置指定為開始位置
               

                return await Task.FromResult(new FileStreamResult(bookStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    FileDownloadName =excelFileName 
            });
            }
            catch (Exception e)
            {
                return null;
            }
        }
}
    public class NpoiExcelExportHelper
    {
        private static NpoiExcelExportHelper _exportHelper;

        public static NpoiExcelExportHelper _
        {
            get => _exportHelper ?? (_exportHelper = new NpoiExcelExportHelper());
            set => _exportHelper = value;
        }

        /// <summary>
        /// TODO:先創(chuàng)建行,然后在創(chuàng)建對應(yīng)的列
        /// 創(chuàng)建Excel中指定的行
        /// </summary>
        /// <param name="sheet">Excel工作表對象</param>
        /// <param name="rowNum">創(chuàng)建第幾行(從0開始)</param>
        /// <param name="rowHeight">行高</param>
        public HSSFRow CreateRow(ISheet sheet, int rowNum, float rowHeight)
        {
            HSSFRow row = (HSSFRow)sheet.CreateRow(rowNum); //創(chuàng)建行
            row.HeightInPoints = rowHeight; //設(shè)置列頭行高
            return row;
        }

        /// <summary>
        /// 創(chuàng)建行內(nèi)指定的單元格
        /// </summary>
        /// <param name="row">需要創(chuàng)建單元格的行</param>
        /// <param name="cellStyle">單元格樣式</param>
        /// <param name="cellNum">創(chuàng)建第幾個單元格(從0開始)</param>
        /// <param name="cellValue">給單元格賦值</param>
        /// <returns></returns>
        public HSSFCell CreateCells(HSSFRow row, HSSFCellStyle cellStyle, int cellNum, string cellValue)
        {
            HSSFCell cell = (HSSFCell)row.CreateCell(cellNum); //創(chuàng)建單元格
            cell.CellStyle = cellStyle; //將樣式綁定到單元格
            if (!string.IsNullOrWhiteSpace(cellValue))
            {
                //單元格賦值
                cell.SetCellValue(cellValue);
            }

            return cell;
        }


        /// <summary>
        /// 行內(nèi)單元格常用樣式設(shè)置
        /// </summary>
        /// <param name="workbook">Excel文件對象</param>
        /// <param name="hAlignment">水平布局方式</param>
        /// <param name="vAlignment">垂直布局方式</param>
        /// <param name="fontHeightInPoints">字體大小</param>
        /// <param name="isAddBorder">是否需要邊框</param>
        /// <param name="boldWeight">字體加粗 (None = 0,Normal = 400,Bold = 700</param>
        /// <param name="fontName">字體(仿宋,楷體,宋體,微軟雅黑...與Excel主題字體相對應(yīng))</param>
        /// <param name="isAddBorderColor">是否增加邊框顏色</param>
        /// <param name="isItalic">是否將文字變?yōu)樾斌w</param>
        /// <param name="isLineFeed">是否自動換行</param>
        /// <param name="isAddCellBackground">是否增加單元格背景顏色</param>
        /// <param name="fillPattern">填充圖案樣式(FineDots 細點,SolidForeground立體前景,isAddFillPattern=true時存在)</param>
        /// <param name="cellBackgroundColor">單元格背景顏色(當isAddCellBackground=true時存在)</param>
        /// <param name="fontColor">字體顏色</param>
        /// <param name="underlineStyle">下劃線樣式(無下劃線[None],單下劃線[Single],雙下劃線[Double],會計用單下劃線[SingleAccounting],會計用雙下劃線[DoubleAccounting])</param>
        /// <param name="typeOffset">字體上標下標(普通默認值[None],上標[Sub],下標[Super]),即字體在單元格內(nèi)的上下偏移量</param>
        /// <param name="isStrikeout">是否顯示刪除線</param>
        /// <returns></returns>
        public HSSFCellStyle CreateStyle(HSSFWorkbook workbook, HorizontalAlignment hAlignment, VerticalAlignment vAlignment, short fontHeightInPoints, bool isAddBorder, short boldWeight, string fontName = "宋體", bool isAddBorderColor = true, bool isItalic = false, bool isLineFeed = false, bool isAddCellBackground = false, FillPattern fillPattern = FillPattern.NoFill, short cellBackgroundColor = HSSFColor.Yellow.Index, short fontColor = HSSFColor.Black.Index, FontUnderlineType underlineStyle =
            FontUnderlineType.None, FontSuperScript typeOffset = FontSuperScript.None, bool isStrikeout = false)
        {
            HSSFCellStyle cellStyle = (HSSFCellStyle)workbook.CreateCellStyle(); //創(chuàng)建列頭單元格實例樣式
            cellStyle.Alignment = hAlignment; //水平居中
            cellStyle.VerticalAlignment = vAlignment; //垂直居中
            cellStyle.WrapText = isLineFeed;//自動換行

            //背景顏色,邊框顏色,字體顏色都是使用 HSSFColor屬性中的對應(yīng)調(diào)色板索引,關(guān)于 HSSFColor 顏色索引對照表,詳情參考:https://www.cnblogs.com/Brainpan/p/5804167.html

            //TODO:引用了NPOI后可通過ICellStyle 接口的 FillForegroundColor 屬性實現(xiàn) Excel 單元格的背景色設(shè)置,F(xiàn)illPattern 為單元格背景色的填充樣式

            //TODO:十分注意,要設(shè)置單元格背景色必須是FillForegroundColor和FillPattern兩個屬性同時設(shè)置,否則是不會顯示背景顏色
            if (isAddCellBackground)
            {
                cellStyle.FillForegroundColor = cellBackgroundColor;//單元格背景顏色
                cellStyle.FillPattern = fillPattern;//填充圖案樣式(FineDots 細點,SolidForeground立體前景)
            }


            //是否增加邊框
            if (isAddBorder)
            {
                //常用的邊框樣式 None(沒有),Thin(細邊框,瘦的),Medium(中等),Dashed(虛線),Dotted(星羅棋布的),Thick(厚的),Double(雙倍),Hair(頭發(fā))[上右下左順序設(shè)置]
                cellStyle.BorderBottom = BorderStyle.Thin;
                cellStyle.BorderRight = BorderStyle.Thin;
                cellStyle.BorderTop = BorderStyle.Thin;
                cellStyle.BorderLeft = BorderStyle.Thin;
            }

            //是否設(shè)置邊框顏色
            if (isAddBorderColor)
            {
                //邊框顏色[上右下左順序設(shè)置]
                cellStyle.TopBorderColor = HSSFColor.DarkGreen.Index;//DarkGreen(黑綠色)
                cellStyle.RightBorderColor = HSSFColor.DarkGreen.Index;
                cellStyle.BottomBorderColor = HSSFColor.DarkGreen.Index;
                cellStyle.LeftBorderColor = HSSFColor.DarkGreen.Index;
            }

            /**
             * 設(shè)置相關(guān)字體樣式
             */
            var cellStyleFont = (HSSFFont)workbook.CreateFont(); //創(chuàng)建字體

            //假如字體大小只需要是粗體的話直接使用下面該屬性即可
            //cellStyleFont.IsBold = true;

            cellStyleFont.Boldweight = boldWeight; //字體加粗
            cellStyleFont.FontHeightInPoints = fontHeightInPoints; //字體大小
            cellStyleFont.FontName = fontName;//字體(仿宋,楷體,宋體 )
            cellStyleFont.Color = fontColor;//設(shè)置字體顏色
            cellStyleFont.IsItalic = isItalic;//是否將文字變?yōu)樾斌w
            cellStyleFont.Underline = underlineStyle;//字體下劃線
            cellStyleFont.TypeOffset = typeOffset;//字體上標下標
            cellStyleFont.IsStrikeout = isStrikeout;//是否有刪除線

            cellStyle.SetFont(cellStyleFont); //將字體綁定到樣式
            return cellStyle;
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容