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

1】excel的佔位符替換

效果如圖數據庫

 

關鍵代碼:app

///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的佔位符替換=》多字段

效果圖ide

        /// <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;

 

4】關於換行符

此處 若是   Environment.NewLine 、<br/>   \n  無效,則建議使用下列換行符 ,但先必須引用 using Aspose.Words;ui

using Aspose.Words;spa

換行符:ControlChar.LineBreak excel

 

列:string ts="測試1"+ControlChar.LineBreak +"測試2";code

相關文章
相關標籤/搜索