C# aspose.words 操作代码实例,封装类

直接上代码吧, 以下是自已写的测试aspose.words 类型的常用操作代码,
操作封装类如下,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MY.COM.Doc
{
public class Word
{
private string _docPath;

    private string _docTempPath;

    private bool _isUnion;

    private string _pwd;

    private Aspose.Words.Document _doc;

    public Word()
    {
        _docTempPath = System.Web.HttpContext.Current.Server.MapPath("/") + "Temp/" + DateTime.Now.ToString("yyMM") + "/COM/Doc/Word/";
        IO.Directory.createIfUnExist(_docTempPath);
        _docTempPath += DateTime.Now.Ticks.ToString() + ".docx";
        _docPath = _docTempPath;
        _doc = new Aspose.Words.Document();

    }
    public Word(string docPath)
    {
        _docTempPath = System.Web.HttpContext.Current.Server.MapPath("/") + "Temp/" + DateTime.Now.ToString("yyMM") + "/COM/Doc/Word/";
        IO.Directory.createIfUnExist(_docTempPath);
        _docTempPath += DateTime.Now.Ticks.ToString() + ".docx";
        this._docPath = docPath;
        _doc = new Aspose.Words.Document(_docPath);
    }

    public Word(string docPath, string pwd)
    {
        _pwd = pwd;
        _docTempPath = System.Web.HttpContext.Current.Server.MapPath("/") + "Temp/" + DateTime.Now.ToString("yyMM") + "/COM/Doc/Word/";
        IO.Directory.createIfUnExist(_docTempPath);
        _docTempPath += DateTime.Now.Ticks.ToString() + ".docx";
        this._docPath = docPath;
        _doc = new Aspose.Words.Document(_docPath, new Aspose.Words.LoadOptions() { Password = pwd });
    }

    /// <summary>
    /// 取得XML内容
    /// </summary>
    /// <returns></returns>
    public string getXML()
    {
        string savePath = System.Web.HttpContext.Current.Server.MapPath("/") + "Temp/" + DateTime.Now.ToString("yyMM") + "/COM/Doc/Word/";
        if (!IO.Directory.createIfUnExist(savePath)) return "ERR:临时文件创建失败";
        savePath += DateTime.Now.Ticks.ToString() + ".xml";
        if (!save(savePath, Aspose.Words.SaveFormat.WordML).StartsWith("OK:")) return "ERR:XML内容临时文件保存出错";
        string reStr = COM.IO.File.getTextStr(savePath, Encoding.UTF8);
        System.IO.File.Delete(savePath);
        return reStr;
    }

    /// <summary>
    /// 取得当前文档页数
    /// </summary>
    /// <returns></returns>
    public int getPageCount()
    {
        return _doc.PageCount;
    }

    /// <summary>
    /// 保存为图片
    /// </summary>
    /// <param name="savePath">图片保存路径</param>
    /// <param name="pageIndex">保存的页码</param>
    /// <returns></returns>
    public string saveToImg(string savePath, int pageNum = 1, Aspose.Words.SaveFormat sf = Aspose.Words.SaveFormat.Jpeg)
    {
        if (_isUnion)
        {
            _doc.Save(_docTempPath, Aspose.Words.SaveFormat.Docx);
            if (string.IsNullOrEmpty(_pwd))
                _doc = new Aspose.Words.Document(_docTempPath);
            else
                _doc = new Aspose.Words.Document(_docTempPath, new Aspose.Words.LoadOptions() { Password = _pwd });
            _isUnion = false;
        }

        Aspose.Words.Saving.ImageSaveOptions options = new Aspose.Words.Saving.ImageSaveOptions(sf);
        options.Resolution = 120;
        options.PrettyFormat = true;
        options.UseAntiAliasing = true;
        if (pageNum > 0)
        {
            if (pageNum > _doc.PageCount)
                return "ERR:超出页码数";
            options.PageIndex = pageNum - 1;
        }

        _doc.Save(savePath, options);
        return "OK:";
    }

    /// <summary>
    /// 保存文档
    /// </summary>
    /// <param name="savePath"></param>
    /// <returns></returns>
    public string save(string savePath, Aspose.Words.SaveFormat sf = Aspose.Words.SaveFormat.Docx)
    {
        if (_isUnion && sf != Aspose.Words.SaveFormat.Docx)
        {
            _doc.Save(_docTempPath, Aspose.Words.SaveFormat.Docx);
            if (string.IsNullOrEmpty(_pwd))
                _doc = new Aspose.Words.Document(_docTempPath);
            else
                _doc = new Aspose.Words.Document(_docTempPath, new Aspose.Words.LoadOptions() { Password = _pwd });
            _isUnion = false;
        }
        _doc.Save(savePath, sf);

        return "OK:";
    }

    public string save()
    {
        _doc.Save(_docPath, Aspose.Words.SaveFormat.Docx);
        return "OK:";
    }

    public string getLoadUrl()
    {
        _doc.Save(_docTempPath, Aspose.Words.SaveFormat.Docx);
        string reUrl = _docTempPath;
        reUrl = reUrl.Replace(System.Web.HttpContext.Current.Server.MapPath("/"), "/");
        return "OK:" + reUrl;
    }

    /// <summary>
    /// 拼接文档
    /// </summary>
    /// <param name="unionDocPath">需拼接的文档</param>
    /// <returns></returns>
    public string unionDoc(string unionDocPath, bool isAddByNewPage = true)
    {
        Aspose.Words.Document UnionDoc = new Aspose.Words.Document(unionDocPath);

        if (isAddByNewPage)
            UnionDoc.FirstSection.PageSetup.SectionStart = Aspose.Words.SectionStart.NewPage;
        else
            UnionDoc.FirstSection.PageSetup.SectionStart = Aspose.Words.SectionStart.Continuous;
        _doc.AppendDocument(UnionDoc, Aspose.Words.ImportFormatMode.KeepSourceFormatting);
        //_doc.AppendDocument(UnionDoc, Aspose.Words.ImportFormatMode.KeepDifferentStyles);
        _isUnion = true;
        return "OK:";
    }

    /// <summary>
    /// 书签写入文字
    /// </summary>
    /// <param name="markName"></param>
    /// <param name="txt"></param>
    /// <param name="isMarkDelete">是否删除书签</param>
    /// <returns></returns>
    public string markToTxt(string markName, string txt, bool isMarkDelete = true)
    {
        foreach (Aspose.Words.Bookmark mark in _doc.Range.Bookmarks)
        {
            if (mark == null) continue;
            if (mark.Name != markName) continue;
            mark.Text = txt;
            if (isMarkDelete) mark.Remove();
            break;
        }
        return "OK:";
    }

    public string markToTxt(string markName, string txt, fontStyle style, bool isMarkDelete = true)
    {
        foreach (Aspose.Words.Bookmark mark in _doc.Range.Bookmarks)
        {
            if (mark == null) continue;
            if (mark.Name != markName) continue;

            Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(_doc);
            builder.MoveToBookmark(mark.Name);

            if (style.color != null) builder.Font.Color = style.color;
            if (!string.IsNullOrEmpty(style.fontName)) builder.Font.Name = style.fontName;
            builder.Font.Bold = style.isBold;
            builder.Font.Italic = style.isItalic;
            if (style.size > 0) builder.Font.Size = style.size;

            mark.Text = "";
            builder.Write(txt);

            if (isMarkDelete) mark.Remove();
            break;
        }
        return "OK:";
    }

    /// <summary>
    /// 书签插入图片
    /// </summary>
    /// <param name="markName">书签名</param>
    /// <param name="imgPath">图片路径</param>
    /// <param name="width">图片长</param>
    /// <param name="height">图片宽</param>
    /// <param name="top">水平离距</param>
    /// <param name="left">直离距</param>
    /// <param name="rhp">水平对齐方式</param>
    /// <param name="rvp">直对齐方式</param>
    /// <param name="wt">图片显示方式</param>
    /// <param name="isBehindText">是否在文字下方(悬浮时)</param>
    /// <param name="isMarkDelete">是否删除书签</param>
    /// <returns></returns>
    public string markToImg(string markName, string imgPath, int width = 150, int height = 150, int top = 0, int left = 0, Aspose.Words.Drawing.RelativeHorizontalPosition rhp = Aspose.Words.Drawing.RelativeHorizontalPosition.Character,
       Aspose.Words.Drawing.RelativeVerticalPosition rvp = Aspose.Words.Drawing.RelativeVerticalPosition.Paragraph,
       Aspose.Words.Drawing.WrapType wt = Aspose.Words.Drawing.WrapType.None, bool isBehindText = true, bool isMarkDelete = true)
    {
        foreach (Aspose.Words.Bookmark mark in _doc.Range.Bookmarks)
        {
            if (mark == null) continue;
            if (mark.Name != markName) continue;
            mark.Text = "";
            Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(_doc);
            if (System.IO.File.Exists(imgPath))
            {
                builder.MoveToBookmark("PHOTO");
                Aspose.Words.Drawing.Shape imgShape = builder.InsertImage(imgPath, rhp, left, rvp, top, width, height, wt);
                imgShape.BehindText = isBehindText;
                if (isMarkDelete) mark.Remove();
                //Aspose.Words.Drawing.WrapType.Through  穿越型
                //Aspose.Words.Drawing.WrapType.None 于文字上方
                //Aspose.Words.Drawing.WrapType.TopBottom 上下型
                //Aspose.Words.Drawing.WrapType.Tight 紧密型
                //Aspose.Words.Drawing.WrapType.Inline 钳入型
                //Aspose.Words.Drawing.WrapType.Square 四周型
            }

            break;
        }
        return "OK:";
    }


    /// <summary>
    /// 表格新增行
    /// </summary>
    /// <param name="tableIndex">操作第几个表格0起</param>
    /// <param name="copyRowIndex">复制第几行格式0起,小于0时默认最后一行</param>
    /// <param name="dv">值列表</param>
    /// <returns></returns>
    public string tableAddRow(int tableIndex, int copyRowIndex, System.Collections.Generic.Dictionary<string, string> dv)
    {
        Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(_doc);

        Aspose.Words.NodeCollection allTables = _doc.GetChildNodes(Aspose.Words.NodeType.Table, true); //拿到所有表格
        Aspose.Words.Tables.Table table = allTables[tableIndex] as Aspose.Words.Tables.Table; //拿到第tableIndex个表格

        Aspose.Words.Node row = copyRowIndex < 0 ? table.LastRow.Clone(true) : table.Rows[copyRowIndex].Clone(true);
        Aspose.Words.Range range = table.LastRow.Range;
        foreach (string key in dv.Keys)
            range.Replace(new System.Text.RegularExpressions.Regex(key), dv[key], new Aspose.Words.Replacing.FindReplaceOptions());
        table.Rows.Add(row); //添加一行

        return "OK:";
    }


    /// <summary>
    /// 删除表格行
    /// </summary>
    /// <param name="tableIndex">操作第几个表格0起</param>
    /// <param name="copyRowIndex">第几行格式0起,小于0时默认最后一行</param>
    /// <returns></returns>
    public string tableDelRow(int tableIndex, int copyRowIndex = -1)
    {
        Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(_doc);

        Aspose.Words.NodeCollection allTables = _doc.GetChildNodes(Aspose.Words.NodeType.Table, true); //拿到所有表格
        Aspose.Words.Tables.Table table = allTables[tableIndex] as Aspose.Words.Tables.Table; //拿到第tableIndex个表格

        if (copyRowIndex < 0)
            table.LastRow.Remove();
        else
            table.Rows[copyRowIndex].Remove();
        return "OK:";
    }

    /// <summary>
    /// 单元格插入图片
    /// </summary>
    /// <param name="tableIndex"></param>
    /// <param name="rowIndex"></param>
    /// <param name="cellIndex"></param>
    /// <param name="imgPath"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public string cellToImg(int tableIndex, int rowIndex, int cellIndex, string imgPath, int width = 150, int height = 150)
    {
        Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(_doc);

        builder.MoveToCell(tableIndex, rowIndex, cellIndex, 0);

        Aspose.Words.Drawing.Shape imgShape = builder.InsertImage(imgPath, Aspose.Words.Drawing.RelativeHorizontalPosition.Column, 0, Aspose.Words.Drawing.RelativeVerticalPosition.Line, 0, width, height, Aspose.Words.Drawing.WrapType.Inline);

        return "OK:";
    }

    public string toProtect(string pwd = "")
    {
        _pwd = pwd;
        if (!string.IsNullOrEmpty(pwd))
            _doc.Protect(Aspose.Words.ProtectionType.AllowOnlyFormFields, pwd);
        else
            _doc.Unprotect();
        return "OK:";
    }

    /// <summary>
    /// 导出word文档里指定的表数据
    /// </summary>
    /// <param name="tableIndex"></param>
    /// <param name="isTitleActive"></param>
    /// <param name="colIndexList"></param>
    /// <returns></returns>
    public System.Data.DataTable getTableData(int tableIndex, bool isTitleActive = true, List<int> colIndexList = null)
    {
        System.Data.DataTable dt = new System.Data.DataTable();

        Aspose.Words.NodeCollection allTables = _doc.GetChildNodes(Aspose.Words.NodeType.Table, true); //拿到所有表格
        Aspose.Words.Tables.Table table = allTables[tableIndex] as Aspose.Words.Tables.Table; //拿到第tableIndex个表格

        int rowIndex = 0;
        int tableColNum = table.Rows[0].Cells.Count;
        if (isTitleActive)
        {
            for (int i = 0, j = tableColNum; i < j; i++)
            {
                if (colIndexList == null || colIndexList.Contains(i))
                    dt.Columns.Add(table.Rows[0].Cells[i].GetText());
            }
            rowIndex++;
        }
        else
        {
            for (int i = 0, j = tableColNum; i < j; i++)
            {
                if (colIndexList == null || colIndexList.Contains(i))
                    dt.Columns.Add(i.ToString());
            }
        }

        for (int iR = rowIndex, jR = table.Rows.Count; iR < jR; iR++)
        {
            System.Data.DataRow dr = dt.NewRow();
            for (int i = 0, j = tableColNum; i < j; i++)
            {
                if (colIndexList == null || colIndexList.Contains(i))
                {
                    if (isTitleActive)
                        dr[table.Rows[0].Cells[i].GetText()] = table.Rows[iR].Cells[i].GetText();
                    else
                        dr[i.ToString()] = table.Rows[iR].Cells[i].GetText();
                }
            }
            dt.Rows.Add(dr);
        }

        return dt;
    }

    public List<Aspose.Words.PageSetup> getSectionPageSetups()
    {
        if (_isUnion)
        {
            _doc.Save(_docTempPath, Aspose.Words.SaveFormat.Docx);
            if (string.IsNullOrEmpty(_pwd))
                _doc = new Aspose.Words.Document(_docTempPath);
            else
                _doc = new Aspose.Words.Document(_docTempPath, new Aspose.Words.LoadOptions() { Password = _pwd });
            _isUnion = false;
        }

        List<Aspose.Words.PageSetup> xList = new List<Aspose.Words.PageSetup>();

        foreach (Aspose.Words.Section sec in _doc)
        {
            xList.Add(sec.PageSetup);
        }

        //xList.ForEach(p => p.PaperSize = Aspose.Words.PaperSize.A4);//全部设置
        //xList[3].PaperSize = Aspose.Words.PaperSize.A4;//单项设置
        return xList;
    }

    public Aspose.Words.PageSetup getPageSetup()
    {
        if (_isUnion)
        {
            _doc.Save(_docTempPath, Aspose.Words.SaveFormat.Docx);
            if (string.IsNullOrEmpty(_pwd))
                _doc = new Aspose.Words.Document(_docTempPath);
            else
                _doc = new Aspose.Words.Document(_docTempPath, new Aspose.Words.LoadOptions() { Password = _pwd });
            _isUnion = false;
        }

        Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(_doc);
        Aspose.Words.PageSetup pageSet = builder.PageSetup;

        //pageSet.PaperSize = Aspose.Words.PaperSize.A4;//设置纸张
        //pageSet.Orientation = Aspose.Words.Orientation.Portrait;//纵向打印模式
        //pageSet.VerticalAlignment = Aspose.Words.PageVerticalAlignment.Top;//顶部靠齐
        //pageSet.TopMargin = 28.35;//以磅为单位返回或设置上边距的大小。Double类型,可读写。此属性与“上”选项对应。
        //pageSet.BottomMargin = 28.35;//以磅为单位返回或设置底端边距的大小。Double类型,可读写。此属性与“下”选项对应。
        //pageSet.RightMargin = 28.35;//以磅为单位返回或设置右边距的大小。Double类型,可读写。此属性与“右”选项对应。
        //pageSet.LeftMargin = 28.35;//以磅为单位返回或设置左边距的大小。Double类型,可读写。此属性与“左”选项对应。
        //pageSet.FooterDistance = 28.35;//以磅为单位返回或设置页脚到页面底端的距离。Double类型,可读写。此属性与“页脚”选项对应。
        //pageSet.HeaderDistance = 28.35;//以磅为单位返回或设置页面顶端到页眉的距离。Double类型,可读写。此属性与“页眉”选项对应。
        1磅约等于0.03527厘米   所以这里可以这样表示 2CM=2/0.03527

        return pageSet;

    }


}

public class fontStyle
{
    /// <summary>
    /// 字体
    /// </summary>
    public string fontName { get; set; }
    /// <summary>
    /// 字体大小
    /// </summary>
    public double size { get; set; }
    //是否加粗
    public bool isBold { get; set; }
    //是否斜体
    public bool isItalic { get; set; }
    /// <summary>
    /// 颜色
    /// </summary>
    public System.Drawing.Color color { get; set; }

}

}

实测代码如下

MY.COM.Doc.Word myword = new MY.COM.Doc.Word(Server.MapPath(“1.docx”));//打开一个现有文档

        MY.COM.Doc.Word myword1 = new MY.COM.Doc.Word(Server.MapPath("1.docx"), "123456");//打开一个加密的现有文档
        MY.COM.Doc.Word myword2 = new MY.COM.Doc.Word();//创建一个空文档

        MY.COM.Doc.Word myword3 = new MY.COM.Doc.Word(Server.MapPath("1.xml"));//打开一个XML文档

        myword.markToTxt("NAME", "测试标签内容写入A");//书签写入文本内容
        myword.markToTxt("NAMEBYSTYLE", "测试标签内容写入B", new MY.COM.Doc.fontStyle() { color = System.Drawing.Color.Red, isBold = true, size = 30 });//书签写入带样式的文本内容

        /// <summary>
        /// 书签插入图片markToImg的参数说明
        /// </summary>
        /// <param name="markName">书签名</param>
        /// <param name="imgPath">图片路径</param>
        /// <param name="width">图片长</param>
        /// <param name="height">图片宽</param>
        /// <param name="top">水平离距</param>
        /// <param name="left">直离距</param>
        /// <param name="rhp">水平对齐方式</param>
        /// <param name="rvp">直对齐方式</param>
        /// <param name="wt">图片显示方式</param>
        /// <param name="isBehindText">是否在文字下方(悬浮时)</param>
        /// <param name="isMarkDelete">是否删除书签</param>
        /// <returns></returns>
        myword.markToImg("PHOTO", Server.MapPath("1.png"), 100, 50);//书签插入图片

        string xmlStr = myword.getXML();//取得XML格式的内容
        int pageNum = myword.getPageCount();//取得文档总页数


        //文档中第二个表[index从0开始],新增一行数据,以最后一行为模板(-1=最后一行),插入的位置为最后上一行
        //示例表如下
        //学生    年级      状态
        //stud    grade     state
        myword.tableAddRow(1, -1, new Dictionary<string, string>()
        {
            {"stud","小明" },
            {"grade","一年级" },
            {"state","正常" },
        });
        myword.tableAddRow(1, -1, new Dictionary<string, string>()
        {
            {"stud","丁丁" },
            {"grade","二年级" },
            {"state","休假" },
        });
        //插入后表为如下
        //学生    年级      状态
        //小明    一年级    正常
        //丁丁    二年级    休假
        //stud    grade     state

        myword.tableDelRow(1, -1);//删除最后一行
        //删除后表为如下
        //学生    年级      状态
        //小明    一年级    正常
        //丁丁    二年级    休假

        //表中指定单元格插入图片
        myword.cellToImg(1, 2, 2, Server.MapPath("1.png"), 100, 50);
        //插入后表为如下
        //学生    年级      状态
        //小明    一年级    正常
        //丁丁    二年级    显示的图片/休假

        myword.unionDoc(Server.MapPath("2.docx"), false);//同页连续拼接文档

        myword.unionDoc(Server.MapPath("2.docx"), true);//另起一页拼接文档

        #region 这样页面设置只能对当前节生效
        //var pageSet = myword.getPageSetup();//取得当前Sheet的页面打印布局对像
        //pageSet.PaperSize = Aspose.Words.PaperSize.A4;//设置纸张
        //pageSet.Orientation = Aspose.Words.Orientation.Landscape;//横向打印模式
        //pageSet.VerticalAlignment = Aspose.Words.PageVerticalAlignment.Top;//顶部靠齐
        //pageSet.TopMargin = 28.35;//以磅为单位返回或设置上边距的大小。Double类型,可读写。此属性与“上”选项对应。
        //pageSet.BottomMargin = 28.35;//以磅为单位返回或设置底端边距的大小。Double类型,可读写。此属性与“下”选项对应。
        //pageSet.RightMargin = 28.35;//以磅为单位返回或设置右边距的大小。Double类型,可读写。此属性与“右”选项对应。
        //pageSet.LeftMargin = 28.35;//以磅为单位返回或设置左边距的大小。Double类型,可读写。此属性与“左”选项对应。
        //pageSet.FooterDistance = 28.35;//以磅为单位返回或设置页脚到页面底端的距离。Double类型,可读写。此属性与“页脚”选项对应。
        //pageSet.HeaderDistance = 28.35;//以磅为单位返回或设置页面顶端到页眉的距离。Double类型,可读写。此属性与“页眉”选项对应。
        //1磅约等于0.03527厘米   所以这里可以这样表示 2CM=2/0.03527
        #endregion


        var sectionPageSets = myword.getSectionPageSetups();

        //以下是对整个文档生效
        //sectionPageSets.ForEach(p => p.PaperSize = Aspose.Words.PaperSize.A4);//设置纸张
        //sectionPageSets.ForEach(p => p.Orientation = Aspose.Words.Orientation.Landscape);//横向打印模式

        //以下是对指定段文档页生效,如拼接了一次,有二个section,则对原文档[0]无效,对拼接的文档有效[1]
        //sectionPageSets[1].PaperSize = Aspose.Words.PaperSize.A4;//设置纸张
        //sectionPageSets[1].Orientation = Aspose.Words.Orientation.Landscape;//横向打印模式


        myword.saveToImg(Server.MapPath("1_3.jpg"), 3);//保存第2页为图片,默认JPG格式
        myword.saveToImg(Server.MapPath("1_2.png"), 2, Aspose.Words.SaveFormat.Png);//保存第3页为图片,png格式

        myword.save(Server.MapPath("1_1.pdf"), Aspose.Words.SaveFormat.Pdf);//保存为PDF文档

        myword.save(Server.MapPath("1_1.docx"));//保存文档
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值