C# 根据模板将数据写入word

参照的下载链接创建的项目接口: C#实现通过模板自动创建Word文档的方法,但是资源是一个txt文件,需要重新手打代码,不过也算是练习了。
在开始之前,我们需要先从nuget安装Microsoft.Office.Interop.Word,下面是代码需要的直接复制就可以,用起来和NPOI还是稍微有些不同。

report.cs
using System;
using System.Diagnostics;
using Microsoft.Office.Interop.Word;

namespace export_doc
{
    public class Report
    {
        private _Application _wordApp = null;
        private _Document _wordDoc = null;

        public _Application Application
        {
            get => _wordApp;
            set => _wordApp = value;
        }

        public _Document Document
        {
            get => _wordDoc;
            set => _wordDoc = value;
        }
        /// 
        /// use template to create new file 
        /// 
        /// 
        public void CreateNewDocument(string path)
        {
            KillWinWordProcess();
            _wordApp = new ApplicationClass()
            {
                DisplayAlerts = WdAlertLevel.wdAlertsNone,
                Visible = false
            };

            object missing = System.Reflection.Missing.Value;
            object templateName = path;
            _wordDoc = _wordApp.Documents.Open(ref templateName, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing);
            
        }
        /// 
        /// save new file
        /// 
        /// 
        public void SaveDocument(string path)
        {
            object fileName = path;
            object format = WdSaveFormat.wdFormatDocument;//save foramt
            object missing = System.Reflection.Missing.Value;
            _wordDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing);
            
            //close _wordDoc , _wordApp
            object saveChanges = WdSaveOptions.wdSaveChanges;
            object originalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
            object routeDocument = false;
            _wordDoc.Close(ref saveChanges,ref originalFormat,ref routeDocument);
            _wordApp.Quit(ref saveChanges,ref originalFormat,ref routeDocument);
        }
        /// 
        /// Insert value to bookMark
        /// 
        /// 
        /// 
        /// 
        public bool InsertValue(string bookMark, string value)
        {
            object bkObj = bookMark;
            if (_wordApp.ActiveDocument.Bookmarks.Exists(bookMark))
            {
                _wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                _wordApp.Selection.TypeText(value);
                return true;
            }
            return false;
        }
        /// 
        /// insert table & bookmark
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public Table InsertTable(string bookMark, int rows, int columns, float width)
        {
            object missing = System.Reflection.Missing.Value;
            object toStart = bookMark;
            Range range = _wordDoc.Bookmarks.get_Item(ref toStart).Range;
            Table newTable = _wordDoc.Tables.Add(range, rows, columns, ref missing, ref missing);
            //set table format
            newTable.Borders.Enable = 1;
            newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;
            if (width != 0)
                newTable.PreferredWidth = width;
            newTable.AllowPageBreaks = false;
            return newTable;
        }
        /// 
        /// merge cells
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2)
        {
            table.Cell(row1,column1).Merge(table.Cell(row2,column2));
        }
        /// 
        /// set table alignment vertical % horizontal
        /// 
        /// 
        /// 
        /// 
        public void SetParagraph_Table(Table table, int align, int vertical)
        {
            switch (align)
            {
                case -1:
                    table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//left align
                    break;
                case 0:
                    table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//center align
                    break;
                case 1:
                    table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;//right align
                    break;
            }

            switch (vertical)
            {
                case -1:
                    table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop;//top align
                    break;
                case 0:
                    table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;//center align
                    break;
                case 1:
                    table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom;//bottom align
                    break;
            }
        }
        /// 
        /// set font name
        /// 
        /// 
        /// 
        /// 
        public void SetFont_Table(Table table, string fontName, double size)
        {
            if (size!=0)
            {
                table.Range.Font.Size = Convert.ToSingle(size);
            }

            if (!string.IsNullOrEmpty(fontName))
            {
                table.Range.Font.Name = fontName;
            }
        }
        /// 
        /// set outline border
        /// 
        /// 
        /// 
        public void UseBorder(int n, bool use)
        {
            // allow has border , default no borders , 1 as line border , 2,3 as dash border
            _wordDoc.Content.Tables[n].Borders.Enable = use ? 1 : 2;
        }
        /// 
        /// add row
        /// 
        /// 
        public void AddRow(int n)
        {
            object missing = System.Reflection.Missing.Value;
            _wordDoc.Content.Tables[n].Rows.Add(ref missing);
        }
        /// 
        /// add rows
        /// 
        /// table number
        /// add rows count
        public void AddRow(int n, int rows)
        {
            object missing = System.Reflection.Missing.Value;
            Table table = _wordDoc.Content.Tables[n];
            for (int i = 0; i < rows; i++)
            {
                table.Rows.Add(ref missing);
            }
        }
        /// 
        /// Insert value to cell 
        /// 
        /// target table
        /// locate row
        /// locate column
        /// value
        public void InsertCell(Table table, int row, int column, string value)
        {
            table.Cell(row, column).Range.Text = value;
        }
        /// 
        /// Insert value to cell
        /// 
        /// table number
        /// locate row
        /// locate column
        /// value
        public void InsertCell(int n, int row, int column, string value)
        {
            _wordDoc.Tables[n].Cell(row, column).Range.Text = value;
        }
        /// 
        /// Insert value to cell
        /// 
        /// table number
        /// locate row
        /// locate column
        /// value array
        public void InsertCell(int n, int row, int columns, string[] values)
        {
            Table table = _wordDoc.Content.Tables[n];
            for (int i = 0; i < columns; i++)
            {
                table.Cell(row, columns).Range.Text = values[i];
            }
        }
        /// 
        /// Insert Picture
        /// 
        /// target bookMark
        /// picture path
        /// picture width
        /// picture height
        public void InsertPicture(string bookMark, string picturePath, float width, float height)
        {
            object missing = System.Reflection.Missing.Value;
            object toStart = bookMark;
            object linkToFile = false;//the picture is link
            object saveWithDocument = true; // save with document
            object range = _wordDoc.Bookmarks.get_Item(ref toStart).Range;//insert picture locate
            _wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
            _wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width;//set picture width
            _wordDoc.Application.ActiveDocument.InlineShapes[1].Height = height;//set picture height
        }
        /// 
        /// Insert Text
        /// 
        /// target bookMark
        /// value
        public void InsertText(string bookMark, string text)
        {
            object toStart = bookMark;
            object range = _wordDoc.Bookmarks.get_Item(ref toStart).Range;
            Paragraph wp = _wordDoc.Content.Paragraphs.Add(ref range);
            wp.Format.SpaceBefore = 6;
            wp.Range.Text = text;
            wp.Format.SpaceAfter = 24;
            wp.Range.InsertParagraphAfter();
            _wordDoc.Paragraphs.Last.Range.Text = "\n";
        }
        /// 
        /// kill word process
        /// 
        public void KillWinWordProcess()
        {
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
            foreach (Process process in processes)
            {
                var b = process.MainWindowTitle == "";
                if (b)
                {
                    process.Kill();
                }
            }
        }
    }
    
   
}

program.cs
namespace export_doc
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            Report report = new Report();
            report.CreateNewDocument(@"xxxxx.docx");
            report.InsertValue("warning_level", "Ⅱ");
            
            report.SaveDocument(@"xxxx.docx");
        }
    }
}

在这里插入图片描述

你可能感兴趣的:(C#,c#)