WPS文档接口学习-C#

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

namespace YLSWTAnalyser
{
    public enum E_YLAlignment
    {
        /// <summary>
        /// 左对齐
        /// </summary>
        LEFT,
        /// <summary>
        /// 居中对齐
        /// </summary>
        CENTER,
        /// <summary>
        /// 右对齐
        /// </summary>
        RIGHT,
    }

    class WPSWordOperator
    {
        private Word.Application _wpsApp; // WPS应用
        private Word.Document _doc; // 当前激活文档
        private Word.Range _ContentRange; // ContentRange 

        public Word.Selection Selection
        {
            get { return _selection; }
        }
        private Word.Selection _selection; //当前选中编辑区

        public string FilePathName
        {
            get { return _filePathName; }
        }
        private string _filePathName = ""; // 文件路径名称(绝对路径)

        public bool Statu
        {
            get { return _statu; }
        }
        private bool _statu = false; // 就绪状态

        /// <summary>
        /// 初始化WPS设置
        /// </summary>
        /// <returns></returns>
        private void Init()
        {
            _wpsApp = new Word.Application();
            _wpsApp.NormalTemplate.Saved = true;
            object myMissing = System.Reflection.Missing.Value;
            _doc = _wpsApp.Documents.Add(ref myMissing, false, 1, true);
            _doc.Activate();
            _selection = _wpsApp.Selection;
            _ContentRange = _doc.Content;

        }
        /// <summary>
        /// 保存到文档
        /// </summary>
        /// <returns></returns>
        public void Save()
        {
            _doc.SaveAs(_filePathName);
            _wpsApp.Quit();
        }
        /// <summary>
        /// 退出WPS
        /// </summary>
        /// <returns></returns>
        public void Quit()
        {
            //_wpsApp.Quit();
            _statu = false;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="filePathName">文件路径名称</param>
        /// <returns></returns>
        public WPSWordOperator(string filePathName)
        {
            _filePathName = filePathName;
            _statu = false;
            Init();
        }
        /// <summary>
        /// 析构函数
        /// </summary>
        /// <returns></returns>
        ~WPSWordOperator()
        {
            Quit();
        }
        /// <summary>
        /// 定位插入点到末尾
        /// </summary>
        /// <returns></returns>
        public void MovePointToLast()
        {
            //_ContentRange.Select();
            _selection.EndKey(WdUnits.wdStory, WdMovementType.wdMove);
        }
        /// <summary>
        /// 插入新段落
        /// </summary>
        /// <returns></returns>
        public void TypePargraph()
        {
            _ContentRange.Select();
            _ContentRange.InsertParagraphAfter();
            _selection.Move(WdUnits.wdLine,1);
        }
        /// <summary>
        /// 插入换页符
        /// </summary>
        /// <returns></returns>
        public void InsertPageBreak()
        {
            _selection.InsertBreak(WdBreakType.wdPageBreak);
        }
        /// <summary>
        /// 页边距设置
        /// </summary>
        /// <returns></returns>
        public void SetPageMargin(float topMargin, float bottomMargin, float leftMargin, float rightMargin)
        {
            _doc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;// 设置纸张大小为A4
            _doc.PageSetup.TopMargin = topMargin;
            _doc.PageSetup.BottomMargin = bottomMargin;
            _doc.PageSetup.LeftMargin = leftMargin;
            _doc.PageSetup.RightMargin = rightMargin;
        }
        /// <summary>
        /// 页眉设置
        /// </summary>
        /// <returns></returns>
        public void SetHeader(string strHeaderText, string fontfamily, int fontSize, E_YLAlignment alignment)
        {
            _wpsApp.ActiveWindow.View.Type = WdViewType.wdNormalView;
            _wpsApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
            switch (alignment)
            {
                case E_YLAlignment.LEFT:
                    _selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;//页眉中的文字右对齐
                    break;
                case E_YLAlignment.CENTER:
                    _selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    break;
                case E_YLAlignment.RIGHT:
                    _selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                    break;
                default:
                    _selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    break;
            }
            _selection.Text = strHeaderText;
            _selection.Font.Name = fontfamily;
            _selection.Font.Size = fontSize;
            _wpsApp.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument; // 退出页眉设置
        }

        /// <summary>
        /// 页脚设置
        /// </summary>
        /// <returns></returns>
        public void SetFooter(string strFooterText, string fontfamily, int fontSize, E_YLAlignment alignment)
        {
            _wpsApp.ActiveWindow.View.Type = WdViewType.wdNormalView;
            _wpsApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryFooter;
            switch (alignment)
            {
                case E_YLAlignment.LEFT:
                    _selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;//页眉中的文字右对齐
                    break;
                case E_YLAlignment.CENTER:
                    _selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    break;
                case E_YLAlignment.RIGHT:
                    _selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                    break;
                default:
                    _selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    break;
            }
            _selection.Text = strFooterText;
            _selection.Range.Text += "\n";
            _selection.Font.Name = fontfamily;
            _selection.Font.Size = fontSize;
            _wpsApp.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument; // 退出页脚设置
        }
        /// <summary>
        /// 页码设置
        /// </summary>
        /// <returns></returns>
        public void SetPageNumber(int startNumber,E_YLAlignment alignment,int style)
        {
            //WdPageNumberAlignment numberAlign = WdPageNumberAlignment.wdAlignPageNumberCenter;
            //switch (alignment)
            //{
            //    case E_YLAlignment.LEFT:
            //        numberAlign = WdPageNumberAlignment.wdAlignPageNumberLeft;
            //        break;
            //    case E_YLAlignment.CENTER:
            //        numberAlign = WdPageNumberAlignment.wdAlignPageNumberCenter;
            //        break;
            //    case E_YLAlignment.RIGHT:
            //        numberAlign = WdPageNumberAlignment.wdAlignPageNumberRight;
            //        break;
            //    default:
            //        break;
            //}
            //Word.PageNumbers pageNumbers = _doc.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers;
            //pageNumbers.StartingNumber = startNumber;
            //pageNumbers.Add(numberAlign, true);
            _wpsApp.ActiveWindow.View.Type = WdViewType.wdNormalView;
            _wpsApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryFooter;
            if (style == 0)
            {
                _selection.Range.Fields.Add(_selection.Range, WdFieldType.wdFieldPage, "{PAGES  \\* MERGEFORMAT}", true);
            }
            else if (style == 1)
            {
                _selection.Range.InsertAfter("-");
                _selection.MoveRight(WdUnits.wdWord, 1);
                _selection.Range.Fields.Add(_selection.Range, WdFieldType.wdFieldPage, "{PAGES  \\* MERGEFORMAT}", true);
                _selection.MoveRight(WdUnits.wdWord, 1);
                _selection.Range.InsertAfter("-");
            }
            else if (style == 2)
            {
                _selection.Range.InsertAfter("第");
                _selection.MoveRight(WdUnits.wdWord, 1);
                _selection.Range.Fields.Add(_selection.Range, WdFieldType.wdFieldPage, "{PAGES  \\* MERGEFORMAT}", true);
                _selection.MoveRight(WdUnits.wdWord, 1);
                _selection.Range.InsertAfter("页");
            }
            else if (style == 3)
            {
                _selection.Range.InsertAfter("第");
                _selection.MoveRight(WdUnits.wdWord, 1);
                _selection.Range.Fields.Add(_selection.Range, WdFieldType.wdFieldPage, "{PAGES  \\* MERGEFORMAT}", true);
                _selection.MoveRight(WdUnits.wdWord, 1);
                _selection.Range.InsertAfter("页");
                _selection.MoveRight(WdUnits.wdWord, 1);
                _selection.Range.InsertAfter("共");
                _selection.MoveRight(WdUnits.wdWord, 1);
                _selection.Range.Fields.Add(_selection.Range, WdFieldType.wdFieldNumPages, "{NUMPAGES  \\* MERGEFORMAT}", true);
                _selection.MoveRight(WdUnits.wdWord, 1);
                _selection.Range.InsertAfter("页");
            }
            switch (alignment)
            {
                case E_YLAlignment.CENTER:
                    _selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    break;
                case E_YLAlignment.LEFT:
                    _selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    break;
                case E_YLAlignment.RIGHT:
                    _selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                    break;
                default:
                    break;
            } 
            _wpsApp.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument; // 退出页脚设置
        }
        /// <summary>
        /// 获取页面主文档区宽度
        /// </summary>
        /// <returns>宽度(磅)</returns>
        public float PageWidth()
        {
            float pageWidth = _doc.PageSetup.PageWidth;
            return _doc.PageSetup.PageWidth - _doc.PageSetup.LeftMargin - _doc.PageSetup.RightMargin;
        }
        /// <summary>
        /// 获取页面主文档区高度
        /// </summary>
        /// <returns>高度(磅)</returns>
        public float PageHeight()
        {
            float pageHeight = _doc.PageSetup.PageHeight;
            float topMargin = _doc.PageSetup.TopMargin;
            float bottomMargin = _doc.PageSetup.BottomMargin;
            return _doc.PageSetup.PageHeight - _doc.PageSetup.TopMargin - _doc.PageSetup.BottomMargin;
        }
        #region 文字操作
        /// <summary>
        /// 插入文字
        /// </summary>
        /// <param name="strText">插入内容</param>
        /// <param name="alignment">对齐方式</param>
        /// <param name="fontFamily">字体族</param>
        /// <param name="size">字体大小</param>
        /// <returns></returns>
        public void InsertText(string strText, E_YLAlignment alignment, string fontFamily = "宋体", int size = 14, bool bBlod = false, bool bItalic = false, bool bUnderLine = false)
        {
            Word.Paragraph parText = _selection.Paragraphs.Last;
            switch (alignment)
            {
                case E_YLAlignment.LEFT:
                    parText.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    break;
                case E_YLAlignment.CENTER:
                    parText.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    break;
                case E_YLAlignment.RIGHT:
                    parText.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                    break;
                default:
                    break;
            }
            parText.Range.Font.Name = fontFamily;
            parText.Range.Font.Size = size;
            parText.Range.Font.Bold = bBlod?1:0;
            parText.Range.Font.Italic = bItalic?1:0;
            parText.Range.Font.Underline = bUnderLine? WdUnderline.wdUnderlineSingle:WdUnderline.wdUnderlineNone;
            parText.Range.Text = strText;
        }
        #endregion

        #region 表格操作
        /// <summary>
        /// 插入表格
        /// </summary>
        /// <param name="rowCnt">行数</param>
        /// <param name="colCnt">列数</param>
        /// <param name="tableTitle">表名</param>
        /// <returns></returns>
        public Word.Table InsertTable(int rowCnt, int colCnt, string tableTitle)
        {
            Word.Paragraph parText = _selection.Paragraphs.Last;
            Word.Tables tables = parText.Range.Tables;
            return tables.Add(parText.Range, rowCnt, colCnt);
        }
        /// <summary>
        /// 单元格插入文字
        /// </summary>
        /// <param name="rowCnt">行数</param>
        /// <param name="colCnt">列数</param>
        /// <param name="text">内容</param>
        /// <returns></returns>
        public void InsertTextToCell(ref Word.Table table, int row, int col, string text,string fontName="宋体",int fontSize = 8)
        {
            Word.Cell cell = table.Cell(row, col);
            cell.Select();
            _selection.Paragraphs.Last.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            cell.Range.Text = text;
            cell.Range.Font.Name = "宋体";
            cell.Range.Font.Size = fontSize;
            cell.Range.Font.Bold = 0;
        }
        /// <summary>
        /// 表格中插入表格
        /// </summary>
        /// <param name="tableContent">被插入的表格对象</param>
        /// <param name="row">插入到第几行</param>
        /// <param name="col">插入到第几列</param>
        /// <param name="subRow">插入表格行数</param>
        ///  <param name="subCol">插入表格函数</param>
        /// <returns></returns>
        public Word.Table InsertTableToCell(ref Word.Table tableContent, int row, int col, int rowCnt, int colCnt)
        {
            Word.Cell cell = tableContent.Cell(row, col);
            Word.Table table = cell.Range.Tables.Add(cell.Range, rowCnt, colCnt);
            cell.TopPadding = 0;
            cell.BottomPadding = 0;
            cell.LeftPadding = 0;
            cell.RightPadding = 0;
            table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleNone;
            table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
            return table;
        }
        /// <summary>
        /// 设置表格列宽
        /// </summary>
        /// <param name="table">被插入的表格对象</param>
        /// 
        /// <returns></returns>
        public void SetTableColumnWidth(ref Word.Table table,float colWidth)
        {
            int rowCount = table.Rows.Count;
            int colCount = table.Columns.Count;
            for (int i = 1; i <= rowCount; ++i)
            {
                for (int n = 1; n <= colCount; ++n)
                {
                    table.Cell(i, n).Width = colWidth;
                }
            }
        }
        /// <summary>
        /// 表格中插入表格
        /// </summary>
        /// <param name="tableContent">被插入的表格对象</param>
        /// <param name="row">插入到第几行</param>
        /// <param name="col">插入到第几列</param>
        /// <param name="picPath">图片路径</param>
        /// <param name="picHeight">图片高度</param>
        /// <param name="picWidth">图片宽度</param>
        /// <returns></returns>
        public Word.InlineShape InsertPicToCell(ref Word.Table tableContent, int row, int col, string picPath)
        {
            Word.Cell cell = tableContent.Cell(row, col);
            Word.InlineShape shape = cell.Range.InlineShapes.AddPicture(picPath, cell.Range);
            cell.TopPadding = 0;
            cell.BottomPadding = 0;
            cell.LeftPadding = 0;
            cell.RightPadding = 0;
            return shape;
        }
        /// <summary>
        /// 合并单元格
        /// </summary>
        /// <param name="tableContent">被插入的表格对象</param>
        /// <param name="row">起始行</param>
        /// <param name="col">起始列</param>
        /// <param name="endRow">结束行</param>
        /// <param name="endCol">结束列</param>
        /// <returns></returns>
        public void MergeTableCell(ref Word.Table table, int startRow, int startCol, int endRow, int endCol)
        {
            int rowCnt = table.Rows.Count;
            int colCnt = table.Columns.Count;
            Word.Cell cellStart = table.Cell(startRow, startCol);
            Word.Cell cellEnd = table.Cell(endRow, endCol);
            cellStart.Merge(cellEnd);
        }
        #endregion

        #region 图片操作
        /// <summary>
        /// 插入图片,在正文中插入图片可用
        /// </summary>
        /// <param name="picName">图片路径</param>
        /// <returns></returns>
        public Word.InlineShape InsertPicture(string picName, string titleName)
        {
            Word.Paragraph parLast = _selection.Paragraphs.Last;
            Word.InlineShapes shapes = parLast.Range.InlineShapes;
            return shapes.AddPicture(picName);
        }
        #endregion
        /// <summary>
        /// 接口测试函数
        /// </summary>
        /// <returns></returns>
        public void Test()
        {
            InsertText("欢迎你学习C#调用WPS", E_YLAlignment.CENTER);
            TypePargraph();
            InsertText("插入表格:",E_YLAlignment.LEFT);

            TypePargraph();
            Word.Table table0 = InsertTable(5, 4, "表1");
            MergeTableCell(ref table0, 5, 1, 5, 4);
            InsertTextToCell(ref table0, 5, 1, "测试插入文字");

            TypePargraph();
            Word.Table table2 = InsertTable(5, 4, "表3");
            MergeTableCell(ref table2, 5, 1, 5, 4);

            InsertPicToCell(ref table2, 5, 1, @"F:\tanwei\study\C#WithWps\WpsTest\WpsTest\bin\x86\Debug\top3.jpe");

            MovePointToLast();
            InsertText("表格2:", E_YLAlignment.LEFT);
            TypePargraph();
            Word.Table table1 = InsertTable(3, 4, "表2");
            Word.Table table_new = InsertTableToCell(ref table1, 3, 3, 5, 5);
            InsertTextToCell(ref table_new, 1, 1, "ssss");
            InsertTextToCell(ref table_new, 3, 2, "aaaa");
            InsertTextToCell(ref table1, 3, 1, "测试插入");

            MovePointToLast();
            InsertText("图1", E_YLAlignment.CENTER);
            TypePargraph();
            Word.InlineShape picShape = InsertPicture(@"F:\tanwei\study\C#WithWps\WpsTest\WpsTest\bin\x86\Debug\top3.jpe","图1");

            TypePargraph();
            InsertText("图2", E_YLAlignment.CENTER);
            TypePargraph();
            Word.InlineShape picShape1 = InsertPicture(@"F:\tanwei\study\C#WithWps\WpsTest\WpsTest\bin\x86\Debug\top3.jpe", "图2");

            Save();
        }
    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
金山文档WPS是一种在线编辑工具,可以帮助用户创建、编辑和共享各种办公文档。.NET是一种开发框架,可用于创建不同类型的应用程序。下面是金山文档WPS在线编辑与.NET的接入指南: 1. 注册API密钥:首先,用户需要在金山文档WPS官方网站上注册一个账号,并获取一个API密钥。 2. 下载和安装SDK:用户需要下载金山文档WPS的.NET SDK,然后根据官方提供的安装指南,将SDK集成到自己的开发环境中。 3. 引入SDK包:在.NET项目中,用户需要将下载的SDK包引入到项目中,以便能够使用金山文档WPS的API接口。 4. 进行身份验证:用户可以使用SDK提供的方法,在应用程序中进行身份验证。用户需要使用之前获取的API密钥进行身份验证,以便能够使用金山文档WPS的编辑功能。 5. 创建和编辑文档:成功进行身份验证后,用户可以使用SDK提供的方法创建、打开和编辑金山文档WPS支持的各种文件格式,如.docx、.xlsx和.pptx等。 6. 保存和分享文档:一旦用户完成了对文档的编辑,可以使用SDK提供的方法保存文档,并可以选择将其分享给其他人或保存到本地设备。 7. 错误处理和异常处理:在使用金山文档WPS的API接口时,用户需要处理可能发生的错误和异常情况,以确保应用程序的稳定性和可靠性。 总之,金山文档WPS在线编辑与.NET的接入指南主要包括注册API密钥、下载和安装SDK、引入SDK包、进行身份验证、创建和编辑文档、保存和分享文档,以及错误处理和异常处理。有了这些步骤的指导,用户就可以在.NET开发环境中轻松地接入和使用金山文档WPS的在线编辑功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值