C# 操作docx文档

 一、需要引用DocX类库文件,可以直接在NuGet中找到。

 二、创建文件,并添加一张表格

        public static string fileName = AppDomain.CurrentDomain.BaseDirectory + "youziku-5.doc";

        public static bool ExistsFile()
        {
            try
            {
                if (File.Exists(fileName)) return true;
                //创建文件
                File.Create(fileName).Close();
using (var document = DocX.Create(fileName)) {
//创建一个1行3列的表格 var table = document.AddTable(1, 3); table.Design = TableDesign.LightList;//边框 table.Alignment = Alignment.center; table.Rows[0].Cells[0].Paragraphs[0].Append("字体名称"); table.Rows[0].Cells[1].Paragraphs[0].Append("字体效果"); table.Rows[0].Cells[2].Paragraphs[0].Append("字体厂商"); var p1 = document.InsertParagraph(); p1.InsertTableAfterSelf(table); // 保存当前文档 document.Save(); } return true; } catch (Exception ex) { Console.WriteLine(ex.Message); return false; } }

三、向表格中追加数据 

  public static string Set(string fontName, string fontCompany)
        {
            try
            {
                //如果不存在文件则创建
                var result = ExistsFile();
                if (!result) return TAjaxCallBack.ERROR;
                using (var document = DocX.Load(fileName))
                {
                    var imgpath = AppDomain.CurrentDomain.BaseDirectory +  "123.png";
                    // 将图像添加到文档中。    
                    var image = document.AddImage(imgpath);
                    var picture = image.CreatePicture();

                    var table = document.Tables[0];
                    var count = table.RowCount;
                    table.InsertRow();
                    table.Rows[count].Cells[0].Paragraphs[0].Append(fontName);
                    table.Rows[count].Cells[1].Paragraphs[0].AppendPicture(picture);
                    table.Rows[count].Cells[2].Paragraphs[0].Append(fontCompany);
                    document.Save();
                }

                return TAjaxCallBack.OK;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return TAjaxCallBack.ERROR;
            }
        }

  

猜你喜欢

转载自www.cnblogs.com/xiaoyaodijun/p/9268982.html