zoukankan      html  css  js  c++  java
  • 关于.net导出数据到excel/word【占位符替换】

    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("
    ", "<br/>");//
    和中文符号必须替换否则报错
                        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;

    4】关于换行符

    此处 如果   Environment.NewLine 、<br/>      无效,则建议使用下列换行符 ,但先必须引用 using Aspose.Words;

    using Aspose.Words;

    换行符:ControlChar.LineBreak 

    列:string ts="测试1"+ControlChar.LineBreak +"测试2";

  • 相关阅读:
    vnode之update 还是没太懂
    vnodec创建之标签
    1054 求平均值
    1053 住房空置率
    1052 卖个萌
    1051 复数乘法
    1050 螺旋矩阵
    1049 数列的片段和
    1048 数字加密
    1047 编程团体赛
  • 原文地址:https://www.cnblogs.com/1439107348s/p/10637355.html
Copyright © 2011-2022 走看看