zoukankan      html  css  js  c++  java
  • c#对Aspose.Word替换书签内容的简单封装

    辅助类1  json和datatable互转:  

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Script.Serialization; //System.Web.Extensions.dll
    using System.Collections;
    using System.Data;
    
    namespace Utils
    {
        public static class JsonDataTableConvert
        {
            #region DataTable 转换为Json 字符串
            /// <summary>
            /// DataTable 对象 转换为Json 字符串
            /// </summary>
            /// <param name="dt"></param>
            /// <returns></returns>
            public static string ToJson(DataTable dt)
            {
                JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
                ArrayList arrayList = new ArrayList();
                foreach (DataRow dataRow in dt.Rows)
                {
                    Dictionary<string, object> dictionary = new Dictionary<string, object>();  //实例化一个参数集合
                    foreach (DataColumn dataColumn in dt.Columns)
                    {
                        dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToStr());
                    }
                    arrayList.Add(dictionary); //ArrayList集合中添加键值
                }
    
                return javaScriptSerializer.Serialize(arrayList);  //返回一个json字符串
            }
            #endregion
    
            #region Json 字符串 转换为 DataTable数据集合
            /// <summary>
            /// Json 字符串 转换为 DataTable数据集合
            /// </summary>
            /// <param name="json"></param>
            /// <returns></returns>
            public static DataTable ToDataTable(string json)
            {
                DataTable dataTable = new DataTable();  //实例化
                DataTable result;
                try
                {
                    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                    javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
                    ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
                    if (arrayList.Count > 0)
                    {
                        foreach (Dictionary<string, object> dictionary in arrayList)
                        {
                            if (dictionary.Keys.Count<string>() == 0)
                            {
                                result = dataTable;
                                return result;
                            }
                            if (dataTable.Columns.Count == 0)
                            {
                                foreach (string current in dictionary.Keys)
                                {
                                    var obj = dictionary[current];
                                    dataTable.Columns.Add(current,typeof(string) /*obj == null ? typeof(string) : obj.GetType()*/);//全当做字符串处理
                                }
                            }
                            DataRow dataRow = dataTable.NewRow();
                            foreach (string current in dictionary.Keys)
                            {
                                dataRow[current] = dictionary[current];
                            }
    
                            dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                        }
                    }
                }
                catch
                {
                }
                result = dataTable;
                return result;
            }
            #endregion
    
            #region 转换为string字符串类型
            /// <summary>
            ///  转换为string字符串类型
            /// </summary>
            /// <param name="s">获取需要转换的值</param>
            /// <param name="format">需要格式化的位数</param>
            /// <returns>返回一个新的字符串</returns>
            public static string ToStr(this object s, string format = "")
            {
                string result = "";
                try
                {
                    if (format == "")
                    {
                        result = s.ToString();
                    }
                    else
                    {
                        result = string.Format("{0:" + format + "}", s);
                    }
                }
                catch
                {
                }
                return result;
            }
            #endregion
        } 
    }


    辅助类2  Excel表格数据和datatable互转:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    using NPOI.HSSF.UserModel;
    using System.IO;
    using System.Data;
    
    namespace Utils
    {
        //http://www.cnblogs.com/luxiaoxun/p/3374992.html
        public class ExcelDataTableConverter : IDisposable
        {
            private string fileName = null; //文件名
            private IWorkbook workbook = null;
            private FileStream fs = null;
            private bool disposed;
    
            public ExcelDataTableConverter(string fileName)
            {
                this.fileName = fileName;
                disposed = false;
            }
    
            /// <summary>
            /// 将DataTable数据导入到excel中
            /// </summary>
            /// <param name="data">要导入的数据</param>
            /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
            /// <param name="sheetName">要导入的excel的sheet的名称</param>
            /// <returns>导入数据行数(包含列名那一行)</returns>
            public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
            {
                int i = 0;
                int j = 0;
                int count = 0;
                ISheet sheet = null;
    
                fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook();
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook();
    
                try
                {
                    if (workbook != null)
                    {
                        sheet = workbook.CreateSheet(sheetName);
                    }
                    else
                    {
                        return -1;
                    }
    
                    if (isColumnWritten == true) //写入DataTable的列名
                    {
                        IRow row = sheet.CreateRow(0);
                        for (j = 0; j < data.Columns.Count; ++j)
                        {
                            row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                        }
                        count = 1;
                    }
                    else
                    {
                        count = 0;
                    }
    
                    for (i = 0; i < data.Rows.Count; ++i)
                    {
                        IRow row = sheet.CreateRow(count);
                        for (j = 0; j < data.Columns.Count; ++j)
                        {
                            row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                        }
                        ++count;
                    }
                    workbook.Write(fs); //写入到excel
                    return count;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: " + ex.Message);
                    return -1;
                }
            }
    
            /// <summary>
            /// 将excel中的数据导入到DataTable中
            /// </summary>
            /// <param name="sheetName">excel工作薄sheet的名称</param>
            /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
            /// <returns>返回的DataTable</returns>
            public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
            {
                ISheet sheet = null;
                DataTable data = new DataTable();
                int startRow = 0;
                try
                {
                    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                    if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                        workbook = new XSSFWorkbook(fs);
                    else if (fileName.IndexOf(".xls") > 0) // 2003版本
                        workbook = new HSSFWorkbook(fs);
    
                    if (sheetName != null)
                    {
                        sheet = workbook.GetSheet(sheetName);
                        if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
                        {
                            sheet = workbook.GetSheetAt(0);
                        }
                    }
                    else
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                    if (sheet != null)
                    {
                        IRow firstRow = sheet.GetRow(0);
                        int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
    
                        if (isFirstRowColumn)
                        {
                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                            {
                                ICell cell = firstRow.GetCell(i);
                                if (cell != null)
                                {
                                    string cellValue = cell.StringCellValue;
                                    if (cellValue != null)
                                    {
                                        DataColumn column = new DataColumn(cellValue);
                                        data.Columns.Add(column);
                                    }
                                }
                            }
                            startRow = sheet.FirstRowNum + 1;
                        }
                        else
                        {
                            startRow = sheet.FirstRowNum;
                        }
    
                        //最后一列的标号
                        int rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)
                        {
                            IRow row = sheet.GetRow(i);
                            if (row == null) continue; //没有数据的行默认是null       
                            
                            DataRow dataRow = data.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                {
                                    //dataRow[j] = row.GetCell(j).ToString();  //19890603会显示成MIDB(C2,7,6)
                                    dataRow[j] = row.GetCell(j).StringCellValue;
                                }
                            }
                            data.Rows.Add(dataRow);
                        }
                    }
    
                    return data;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: " + ex.Message);
                    return null;
                }
            }
    
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
    
            protected virtual void Dispose(bool disposing)
            {
                if (!this.disposed)
                {
                    if (disposing)
                    {
                        if (fs != null)
                            fs.Close();
                    }
    
                    fs = null;
                    disposed = true;
                }
            }
        }
    }


    书签内容替换封装:


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Aspose.Words;
    using System.Data;
    
    namespace Utils
    {
        public static class AsposeWordReplaceBookMarkContentApi
        {
            public static void BookMarkReplace(Document wordDoc,DocumentBuilder builder, string bookMark, string type, string value)
            {
                var bm = wordDoc.Range.Bookmarks[bookMark];
                if (bm == null)
                {
                    return;
                }
                
                
                if (type == "IMG")
                {
                    bm.Text = "";
                    builder.MoveToBookmark(bookMark);
                    var img = builder.InsertImage(@value);
                    //img.Width = 300;
                    //img.Height = 300;
                   <span style="color:#ff0000;">img.Width =ConvertUtil.PixelToPoint(124d); //单位转换</span>
              img.Height = ConvertUtil.PixelToPoint(134d);
                    img.HorizontalAlignment = Aspose.Words.Drawing.HorizontalAlignment.Center;
                }
                else if (type == "TABLE")
                {
                    bm.Text = "";
                    builder.MoveToBookmark(bookMark);
    
                    DataTable dt = Utils.JsonDataTableConvert.ToDataTable(value);//json转datatable
    
                    int rowCount = dt.Rows.Count;
                    int columnCount = dt.Columns.Count;
    
                    builder.MoveToBookmark(bookMark);
                    builder.StartTable();//开始画Table            
                    builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; // RowAlignment.Center;                
    
                    string str = string.Empty;
    
                    builder.RowFormat.Height = 20;
    
                    //添加列头
                    for (int i = 0; i < columnCount; i++)
                    {
                        builder.InsertCell();
                        //Table单元格边框线样式
                        builder.CellFormat.Borders.LineStyle = LineStyle.Single;
                        //Table此单元格宽度
                        builder.CellFormat.Width = 600;
                        //此单元格中内容垂直对齐方式
                        builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;
                        builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
                        builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                        //字体大小
                        builder.Font.Size = 10;
                        //是否加粗
                        builder.Bold = true;
                        //向此单元格中添加内容
                        builder.Write(dt.Columns[i].ColumnName);
                    }
                    builder.EndRow();
    
                    //添加每行数据
                    for (int i = 0; i < rowCount; i++)
                    {
    
    
                        for (int j = 0; j < columnCount; j++)
                        {
                            str = dt.Rows[i][j].ToString();
    
                            //http://www.cnblogs.com/geovindu/p/4106418.html
                            //http://www.cnblogs.com/wuhuacong/archive/2012/08/30/2662961.html
    
                            //插入Table单元格
                            builder.InsertCell();
    
                            //Table单元格边框线样式
                            builder.CellFormat.Borders.LineStyle = LineStyle.Single;
    
                            //Table此单元格宽度 跟随列头宽度
                            //builder.CellFormat.Width = 500;
    
                            //此单元格中内容垂直对齐方式
                            builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;
    
                            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
                            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
    
                            //字体大小
                            builder.Font.Size = 10;
    
                            //是否加粗
                            builder.Bold = false;
    
                            //向此单元格中添加内容
                            builder.Write(str);
    
                        }
    
                        //Table行结束
                        builder.EndRow();
    
                    }
                    builder.EndTable();
                }
                else
                {//其他文字,日期等文字
                    bm.Text = "";
                    builder.MoveToBookmark(bookMark);
                    bm.Text =@value;
                }
    
    
    
    
            }
    
        }
    }
    


    调用:

            private void button2_Click(object sender, EventArgs e)
            {
                Aspose.Words.Document doc = new Aspose.Words.Document("TEMPLATE.DOCX");
                Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);
    
                //在书签处插入表格
                Utils.AsposeWordReplaceBookMarkContentApi.BookMarkReplace(doc, builder, "BK002", "TABLE", "[{'Name':'zhangsan','Sex':'Male'},{'Name':'wangwu','Sex':'Female'}]");
                //在书签处插入图片
                Utils.AsposeWordReplaceBookMarkContentApi.BookMarkReplace(doc, builder, "BK001", "IMG", "1.PNG");
                //在书签处插入文字
                Utils.AsposeWordReplaceBookMarkContentApi.BookMarkReplace(doc, builder, "BK003", "TEXT", "  测试文字啊啊涉及到法律框架阿斯兰开发按时交电费卡拉斯几发,阿斯顿减肥拉斯加付款阿卡丽交电费卡拉斯发的,看到谁放假啦设计费看,开始搭建费绿卡是否看见快乐健康了阿斯顿发顺丰空间看拉丁方.");
    
                string saveDocFile = "1.DOCX";
                doc.Save(saveDocFile);
               
                if (MessageBox.Show("保存成功,是否打开文件?", "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(saveDocFile);
                }
            }


    效果:


     

    打印

    doc.Print();

     文本替换

    doc.Range.Replace("{{name}}", "张三", false, true);

    版权声明:本文为博主原创文章,未经博主允许不得转载。

    作者:xuejianxiyang
    出处:http://xuejianxiyang.cnblogs.com
    关于作者:Heaven helps those who help themselves.
    本文版权归原作者和博客园共有,欢迎转载,但未经原作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    LyX – The Document Processor
    An HTML5 presentation builder — Read more
    R语言定义
    A Hybrid User and ItemBased Collaborative Filtering with Smoothing on Sparse Data
    RapidMiner
    http://www.rseek.org一个查找R资料的站点
    An HTML5 presentation builder — Read more
    R代码脚本的运行
    data ming with R a book
    A Hybrid User and ItemBased Collaborative Filtering with Smoothing on Sparse Data
  • 原文地址:https://www.cnblogs.com/xuejianxiyang/p/4862070.html
Copyright © 2011-2022 走看看