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;
        }
        /// <summary>
        /// use template to create new file 
        /// </summary>
        /// <param name="path"></param>
        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);
            
        }
        /// <summary>
        /// save new file
        /// </summary>
        /// <param name="path"></param>
        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);
        }
        /// <summary>
        /// Insert value to bookMark
        /// </summary>
        /// <param name="bookMark"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        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;
        }
        /// <summary>
        /// insert table & bookmark
        /// </summary>
        /// <param name="bookMark"></param>
        /// <param name="rows"></param>
        /// <param name="columns"></param>
        /// <param name="width"></param>
        /// <returns></returns>
        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;
        }
        /// <summary>
        /// merge cells
        /// </summary>
        /// <param name="table"></param>
        /// <param name="row1"></param>
        /// <param name="column1"></param>
        /// <param name="row2"></param>
        /// <param name="column2"></param>
        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));
        }
        /// <summary>
        /// set table alignment vertical % horizontal
        /// </summary>
        /// <param name="table"></param>
        /// <param name="align"></param>
        /// <param name="vertical"></param>
        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;
            }
        }
        /// <summary>
        /// set font name
        /// </summary>
        /// <param name="table"></param>
        /// <param name="fontName"></param>
        /// <param name="size"></param>
        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;
            }
        }
        /// <summary>
        /// set outline border
        /// </summary>
        /// <param name="n"></param>
        /// <param name="use"></param>
        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;
        }
        /// <summary>
        /// add row
        /// </summary>
        /// <param name="n"></param>
        public void AddRow(int n)
        {
            object missing = System.Reflection.Missing.Value;
            _wordDoc.Content.Tables[n].Rows.Add(ref missing);
        }
        /// <summary>
        /// add rows
        /// </summary>
        /// <param name="n">table number</param>
        /// <param name="rows">add rows count</param>
        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);
            }
        }
        /// <summary>
        /// Insert value to cell 
        /// </summary>
        /// <param name="table">target table</param>
        /// <param name="row">locate row</param>
        /// <param name="column">locate column</param>
        /// <param name="value">value</param>
        public void InsertCell(Table table, int row, int column, string value)
        {
            table.Cell(row, column).Range.Text = value;
        }
        /// <summary>
        /// Insert value to cell
        /// </summary>
        /// <param name="n">table number</param>
        /// <param name="row">locate row</param>
        /// <param name="column">locate column</param>
        /// <param name="value">value</param>
        public void InsertCell(int n, int row, int column, string value)
        {
            _wordDoc.Tables[n].Cell(row, column).Range.Text = value;
        }
        /// <summary>
        /// Insert value to cell
        /// </summary>
        /// <param name="n">table number</param>
        /// <param name="row">locate row</param>
        /// <param name="columns">locate column</param>
        /// <param name="values">value array</param>
        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];
            }
        }
        /// <summary>
        /// Insert Picture
        /// </summary>
        /// <param name="bookMark">target bookMark</param>
        /// <param name="picturePath">picture path</param>
        /// <param name="width">picture width</param>
        /// <param name="height">picture height</param>
        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
        }
        /// <summary>
        /// Insert Text
        /// </summary>
        /// <param name="bookMark">target bookMark</param>
        /// <param name="text">value</param>
        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";
        }
        /// <summary>
        /// kill word process
        /// </summary>
        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");
        }
    }
}

在这里插入图片描述

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值