關於.net導出數據到excel/word【占位符替換】

来源:https://www.cnblogs.com/1439107348s/archive/2019/04/01/10637355.html
-Advertisement-
Play Games

1】excel的占位符替換 效果如圖 關鍵代碼: ///savedFilePath需要保存的路徑 templateDocPath模板路徑 替換的關鍵字和值 格式 [姓名]$%$小王 public static void ReadExcel(string savedFilePath, string t ...


1】excel的占位符替換

效果如圖

 

關鍵代碼:

///savedFilePath需要保存的路徑  templateDocPath模板路徑  替換的關鍵字和值  格式  [姓名]$%$小王
public static void ReadExcel(string savedFilePath, string templateDocPath,  List<string> ReArray)
        {

            try
            {
                //載入可讀可寫文件流 
                using (FileStream stream = new FileStream(templateDocPath, FileMode.Open, FileAccess.Read))
                {
                    IWorkbook workbook = WorkbookFactory.Create(stream);//使用介面,自動識別excel2003/2007格式
                    ISheet sheet = workbook.GetSheetAt(0);//得到裡面第一個sheet
                    IRow row = null;
                    ICell cell = null;

                    //1讀取符合條件的
                    Regex reg = new Regex(@"\[\S+?\]", RegexOptions.Singleline);
                    List<string> getList = new List<string>();
                    for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
                    {
                        row = sheet.GetRow(i);
                        for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
                        {
                            cell = row.GetCell(j);
                            if (cell != null)
                            {
                                if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                                {
                                    var currentCellVal = cell.StringCellValue;
                                    if (reg.IsMatch(currentCellVal))
                                    {
                                        MatchCollection listsCollection = reg.Matches(currentCellVal);
                                        for (int jNum = 0; jNum < listsCollection.Count; jNum++)
                                        {
                                            var aa = listsCollection[jNum].Value;
                                            getList.Add(aa);
                                        }
                                    }
                                }
                            }

                        }
                    }


                    //2替換

                    for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
                    {
                        row = sheet.GetRow(i);
                        for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
                        {

                            cell = row.GetCell(j);
                            if (cell != null)
                            {
                                foreach (var item in getList)
                                {
                                    string getX = cell.StringCellValue;
                                    if (getX.Contains(item))
                                    {
                                        foreach (var itemRa in ReArray)
                                        {

                                            var getValue = itemRa.Split(new string[] { "$%$" }, StringSplitOptions.None);
                                            if (item == getValue[0])
                                            {
                                                getX = getX.Replace(item, getValue[1]);
                                                cell.SetCellValue(getX);
                                            }

                                        }

                                    }
                                }
                                //刪除沒有的數據   此處是excel中需要替換的關鍵字,但是資料庫替換中卻沒有的,用空值代替原來“[關鍵字]”
                                string getXNull = cell.StringCellValue;
                                MatchCollection listsCollection = reg.Matches(getXNull);
                                if (listsCollection.Count > 0)
                                {
                                    var valNull = getXNull;
                                    getXNull = getXNull.Replace(valNull, "");
                                    cell.SetCellValue(getXNull);
                                }





                            }
                        }
                    }
                    //新建一個文件流,用於替換後的excel保存文件。
                    FileStream success = new FileStream(savedFilePath, FileMode.Create);
                    workbook.Write(success);
                    success.Close(); 
                }


            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
        }
View Code

 

2】word的占位符替換

 /// <summary>
        /// world自定義模板導出
        /// </summary>
        /// <param name="savedFilePath">保存路勁</param>
        /// <param name="templateDocPath">獲取模板的路徑</param>
        /// <param name="ReArray">需要替換的值    [姓名]$%$張三</param> 
        /// 
        public static void ReadWord(string savedFilePath, string templateDocPath, List<string> ReArray)
        {

            try
            {
                #region 進行替換


                Aspose.Words.Document doc = new Aspose.Words.Document(templateDocPath);
                DocumentBuilder builder = new DocumentBuilder(doc);
                foreach (var item in ReArray)
                {
                    var reA = item.Split(new string[] { "$%$" }, StringSplitOptions.None);
                    string oneValue = reA[0];
                    string towValue = ToDBC(reA[1]).Replace("\r", "<br/>");//\r和中文符號必須替換否則報錯
                    doc.Range.Replace(oneValue, towValue, false, false);
                }
                doc.Save(savedFilePath);//也可以保存為1.doc 相容03-07 

                #endregion

            }
            catch (Exception ex)
            {

                throw;
            }
        }
View Code

3】excel的占位符替換=》多欄位

效果圖

        /// <summary>
        /// 根據模版導出Excel
        /// </summary>
        /// <param name="templateFile">模版路徑(包含尾碼)  例:"/Template/Exceltest.xls"</param>
        /// <param name="strFileName">文件名稱(不包含尾碼)  例:"Excel測試"</param>
        /// <param name="source">源DataTable</param>
        /// <param name="cellKes">需要導出的對應的列欄位  例:string[] cellKes = { "name","sex" };</param>
        /// <param name="rowIndex">從第幾行開始創建數據行,第一行為0</param>
        /// <returns>是否導出成功</returns>
        public static string ExportScMeeting(string templateFile, string strFileName, DataTable source, List<string> cellKes, int rowIndex)
        {
            templateFile = HttpContext.Current.Server.MapPath(templateFile);
            int cellCount = cellKes.Count();//總列數,第一列為0
            IWorkbook workbook = null;
            try
            {
                using (FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read))
                {


                    workbook = WorkbookFactory.Create(file);
                    //if (Path.GetExtension(templateFile) == ".xls")
                    //    workbook = new HSSFWorkbook(file);
                    //else if (Path.GetExtension(templateFile) == ".xlsx")
                    //    workbook = new XSSFWorkbook(file);
                }
                ISheet sheet = workbook.GetSheetAt(0);
                if (sheet != null && source != null && source.Rows.Count > 0)
                {
                    IRow row; ICell cell;
                    //獲取需插入數據的首行樣式
                    IRow styleRow = sheet.GetRow(rowIndex);
                    if (styleRow == null)
                    {
                        for (int i = 0, len = source.Rows.Count; i < len; i++)
                        {
                            row = sheet.CreateRow(rowIndex);
                            //創建列並插入數據
                            for (int index = 0; index < cellCount; index++)
                            {
                                row.CreateCell(index)
                                    .SetCellValue(!(source.Rows[i][cellKes[index]] is DBNull) ? source.Rows[i][cellKes[index]].ToString() : string.Empty);
                            }
                            rowIndex++;
                        }
                    }
                    else
                    {
                        for (int i = 0, len = source.Rows.Count; i < len; i++)
                        {
                            row = sheet.CreateRow(rowIndex);
                            row.HeightInPoints = styleRow.HeightInPoints;
                            row.Height = styleRow.Height;
                            //創建列並插入數據
                            for (int index = 0; index < cellCount; index++)
                            {
                                var tx = source.Rows[i][cellKes[index]];
                                var tc = styleRow.GetCell(index).CellType;

                                cell = row.CreateCell(index, styleRow.GetCell(index).CellType);
                                cell.CellStyle = styleRow.GetCell(index).CellStyle;
                                cell.SetCellValue(!(source.Rows[i][cellKes[index]] is DBNull) ? source.Rows[i][cellKes[index]].ToString() : string.Empty);
                            }
                            rowIndex++;
                        }
                    }
                }
                return NPOIExport(strFileName + "." + templateFile.Split('.')[templateFile.Split('.').Length - 1], workbook);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }


                public static string NPOIExport(string fileName, IWorkbook workbook)
        {
            try
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                workbook.Write(ms);

                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
                ms.Close();
                ms.Dispose();
                return "導出成功";
            }
            catch (Exception ex)
            {
                return "導出失敗";
            }
        }
View Code

 

另外,需要引用的using也一同貼圖

using Aspose.Words;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;

 


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

-Advertisement-
Play Games
更多相關文章
  • 和WPF數字滾動抽獎有區別,WPF數字滾動抽獎是隨機的,而這裡是確定的。 為了系統演示,這個效果通宵加班寫了整整6個小時,中間就上了次廁所。 有點小BUG改天再改。 代碼: RollingNumberItemCtrl.xaml代碼: <UserControl x:Class="SunCreate.C ...
  • 語言的設計,真的是挺有意思的。第一次看這個代碼[1]時,旁人隨口了一句“哇,好多實心句號”。 當時馬上一個想法是——怎麼實現的?返回了對象,然後再調用方法?然後就放下了,後來發現,這個是真值得說一說的。 1. 神奇的鏈接(chaining) 1.1 拓展方法 想了很久該怎麼引入話題,或者這樣說,像這 ...
  • <div class="text-center"> <span style="display:inline-block; position:relative;top:-30px;">共 @Model.TotalPageCount 頁 @Model.TotalItemCount 條記錄,當前為第 @M ...
  • 最近在做項目的時候出現了一個錯誤 當從資料庫中獲取值的時候 報錯:空對象不能轉換為值類型 因為資料庫你查詢數據的時候不是所有的欄位都是存在數據的,有些欄位可能是Null值,也就是沒有數據 當你在類型轉換的時候就有可能出現這種錯誤 在網上也查找了相關的資料,底子也不是特別的好 C#在2.0的使用引用的 ...
  • C# Split的用法,Split分割字元串 ...
  • 問題:當我們將4.0的項目修改成為4.5時,會出現以下問題 分析原因: 首先,webform自帶的驗證是有載入jquery組件包。因為使用了webform自帶的驗證,將框架修改為4.5版本時,程式預設識別的jquery組件包還是4.0的,導致組件包無法引入,造成jquery引入異常。 你可以通過查看 ...
  • C# 直接引用js文件,調js里的數據 引入命名空間 using System.IO; string path = AppDomain.CurrentDomain.BaseDirectory + "/content/js/branddata.js"; string str2 = File.ReadA ...
  • 1後臺代碼 2】前端js代碼 3】body中的代碼 ...
一周排行
    -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.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...