Word.Activities的一些设计思路

浏览:1086 发布日期:2023-06-28 16:41:42

实现若干个获取word插入点的活动:

TableRange:

PageRange:

ParagraphRange:

表格前,表格后

指定页开始:

插入点可以通过:range的位置来指定

WordInsertImage:

插入点

向word插入图片:

WordCell
public class WordCell
{
    public string Text { get; set; }

    public WordCell() { }

    public WordCell(string text)
    {
        this.Text = text;
    }

    public WordCell(Range range)
    {
        this.Text = range.Text;
    }

    public override bool Equals(object obj)
    {
        return obj is WordCell cell &&
               Text == cell.Text;
    }

    public override int GetHashCode()
    {
        return 1249999374 + EqualityComparer<string>.Default.GetHashCode(Text);
    }
}

WordRow

public class WordRow
{
    public List<WordCell> Cells { get; set; }

    public WordRow()
    {
        this.Cells = new List<WordCell>();
    }

    public override bool Equals(object obj)
    {
        return obj is WordRow row &&
               EqualityComparer<List<WordCell>>.Default.Equals(Cells, row.Cells);
    }

    public override int GetHashCode()
    {
        return -2012357342 + EqualityComparer<List<WordCell>>.Default.GetHashCode(Cells);
    }
}

WordRange

/// <summary>
/// 表示Word中的一段范围
/// </summary>
public class WordRange
{
    public int Start { get; set; }

    public int End { get; set; }

    public WordRange(int start, int end)
    {

    }
}

WordTable

public class WordTable
{
    public List<WordRow> Rows { get; set; }
    /// <summary>
    /// 记录更新的单元格信息,键为行索引,值为列索引HashSet,索引从0开始
    /// </summary>
    public Dictionary<int, HashSet<int>> ChangedCellDict { get; private set; } = new Dictionary<int, HashSet<int>>();

    public WordTable() 
    { 
        this.Rows = new List<WordRow>();
        this.ChangedCellDict = new Dictionary<int, HashSet<int>>();
    }

    public WordTable(word.Table table)
    {
        this.Rows = new List<WordRow>();
        this.ChangedCellDict = new Dictionary<int, HashSet<int>>();
        foreach (word.Row r in table.Rows)
        {
            WordRow row = new WordRow();
            this.Rows.Add(row);
            for (int i = 0; i < r.Cells.Count; i++)
            {
                WordCell cell = new WordCell(r.Cells[i + 1].Range);
                row.Cells.Add(cell);
            }
        }
    }

    public WordCell this[int row, int col]
    {
        get
        {
            if (row >= 0 && row < this.Rows.Count)
            {
                if (col >= 0 && col <= this.Rows[row].Cells.Count)
                {
                    return this.Rows[row].Cells[col];
                }
                else
                {
                    throw new Exception(String.Format("行列值无效:row: {0}, col: {1}", row, col));
                }
            }
            else
            {
                throw new Exception(String.Format("行列值无效:row: {0}, col: {1}", row, col));
            }
        }
        set
        {
            if (row >= 0 && row < this.Rows.Count)
            {
                if (col >= 0 && col <= this.Rows[row].Cells.Count)
                {
                    this.Rows[row].Cells[col] = value;

                    if (!this.ChangedCellDict.ContainsKey(row))
                    {
                        this.ChangedCellDict.Add(row, new HashSet<int>());
                    }
                    this.ChangedCellDict[row].Add(col);
                }
                else
                {
                    throw new Exception(String.Format("行列值无效:row: {0}, col: {1}", row, col));
                }
            }
            else
            {
                throw new Exception(String.Format("行列值无效:row: {0}, col: {1}", row, col));
            }
        }
    }

    public void SetCellValue(int row, int col, string val)
    {
        WordCell cell = new WordCell(val);
        this[row, col] = cell;
    }

    public override bool Equals(object obj)
    {
        return obj is WordTable table &&
               EqualityComparer<List<WordRow>>.Default.Equals(Rows, table.Rows);
    }

    public override int GetHashCode()
    {
        return 1393792888 + EqualityComparer<List<WordRow>>.Default.GetHashCode(Rows);
    }
}

WordParagraph

/// <summary>
/// 表示word中的一个段落
/// </summary>
public class WordParagraph
{
    public string Text { get; set; }
    public bool IsNew { get; set; }
    public bool IsDel { get; set; }
    public WordRange WordRange { get; set; }

    public WordParagraph()
    {
        this.Text = string.Empty;
        this.IsNew = false;
        this.IsDel = false;
    }

    public WordParagraph(word.Range range)
    {
        this.Text = range.Text;
    }

    public WordParagraph(string text, bool isNew = false, bool isDel = false)
    {
        this.Text = text;
        this.IsNew = isNew;
        this.IsDel = isDel;
    }

    public override bool Equals(object obj)
    {
        return obj is WordParagraph paragraph &&
               Text == paragraph.Text &&
               IsNew == paragraph.IsNew &&
               IsDel == paragraph.IsDel;
    }

    public override int GetHashCode()
    {
        int hashCode = -1994016191;
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Text);
        hashCode = hashCode * -1521134295 + IsNew.GetHashCode();
        hashCode = hashCode * -1521134295 + IsDel.GetHashCode();
        return hashCode;
    }
}

WordDocument

public class WordDocument { protected Application WordApp; /// 

/// 标志,是否应该自动退出,只会关闭自己打开的Word文件 /// private bool Quit = true;


public Document Document { get; set; }

public bool QuitOnDisose { get; set; }

public bool AutoSave { get; set; } = true;

public WordDocument(string documentPath)
{
    documentPath = Path.GetFullPath(documentPath);
    if (!File.Exists(documentPath) && !Path.HasExtension(documentPath))
    {
        documentPath += ".docx";
    }
    if (this.WordApp == null)
    {
        try
        {
            this.WordApp = Marshal.GetActiveObject("Word.Application") as Application;
            foreach (Document doc in this.WordApp.Documents)
            {
                if (documentPath == doc.FullName)
                {
                    this.Document = doc;
                    this.Quit = false;
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("获取WordApp异常信息:{0}", ex.Message);
            Trace.TraceError(ex.ToString());
        }
    }

    if (this.WordApp == null)
    {
        try
        {
            this.WordApp = Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("000209FF-0000-0000-C000-000000000046"))) as Application;
            this.WordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
        }
        catch
        {
            throw new WordException("没有找到Word程序");
        }
    }

    Documents docs;
    try
    {
        docs = this.WordApp.Documents;
    }
    catch
    {
        throw new WordException("没有找到Word程序");
    }

    if (File.Exists(documentPath))
    {
        this.Document = docs.Open(documentPath);
        this.WordApp.Visible = true;
        this.Document.Activate();
    }
    else
    {
        throw new WordException(String.Format("文件路径:{0}不存在。", documentPath));
    }
}

public void autoSaveDocument()
{
    if (this.AutoSave)
    {
        this.Document?.Save();
    }
}

public void CloseDocument()
{
    try
    {
        if (this.Quit)
        {
            if (this.Document != null)
            {
                this.Document.Close();
            }
            if (this.WordApp != null)
            {
                this.WordApp.Quit();
            }
        }
    }
    catch (Exception ex)
    {
        Trace.TraceError(ex.ToString());
    }
}

private void releaseComObjects()
{
    if (this.Document != null)
    {

    }
}

}