C# 生成word文档(NPOI.XWPF)

本文介绍了如何使用C#和NPOI库来创建Word文档,包括插入特殊字符、渲染Word模板、指定位置插入行、在表格内设置字体样式以及解决模板渲染替换问题的方法。通过项目搭建、代码示例和实践案例,详细阐述了整个过程。
摘要由CSDN通过智能技术生成

一、基础

1、创建Word

using NPOI.XWPF.UserModel
        XWPFDocument doc = new XWPFDocument();      //创建新的word文档
        
        XWPFParagraph p1 = doc.CreateParagraph();   //向新文档中添加段落
        p1.SetAlignment(ParagraphAlignment.CENTER); //段落对其方式为居中

        XWPFRun r1 = p1.CreateRun();                //向该段落中添加文字
        r1.SetText("测试段落一");

        XWPFParagraph p2 = doc.CreateParagraph();
        p2.SetAlignment(ParagraphAlignment.LEFT);

        XWPFRun r2 = p2.CreateRun();
        r2.SetText("测试段落二");
     r2.SetFontSize(16);//设置字体大小
       r2.SetBlod(true);//设置粗体

        FileStream sw = File.Create("cutput.docx"); //...
        doc.Write(sw);                              //...
        sw.Close();                                 //在服务端生成文件

        FileInfo file = new FileInfo("cutput.docx");//文件保存路径及名称  
                                                    //注意: 文件保存的父文件夹需添加Everyone用户,并给予其完全控制权限
        Response.Clear();
        Response.ClearHeaders();
        Response.Buffer = false;
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" 
            + HttpUtility.UrlEncode("output.docx", System.Text.Encoding.UTF8));
        Response.AppendHeader("Content-Length", file.Length.ToString());
        Response.WriteFile(file.FullName);
        Response.Flush();                           //以上将生成的word文件发送至用户浏览器

        File.Delete("cutput.docx");

2、特殊字符

代码实现起来很简单。

run之前的代码就不写了。大家可以网上搜索。

run.FontFamily = "Wingdings 2";//这边是特殊字符的字体
text = text.Replace("name", Convert.ToChar(0x0052).ToString());//0x0052是特殊字符的十六进制代码
//text = text.Replace("name", "R");//该代码也可以实现(0x0052对应的字符就是R)

3、NOPI读取Word模板并渲染保存

using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;


namespace TestNPOI
{
    public class NPOIHleper
    {

        public static void Export()
        {
            string filepath = HttpContext.Current.Server.MapPath("~/simpleTable.docx");
            var tt = new  { name = "cjc", age = 29 };
            using (FileStream stream = File.OpenRead(filepath))
            {
                XWPFDocument doc = new XWPFDocument(stream);
                //遍历段落                  
                foreach (var para in doc.Paragraphs)
                {
                    ReplaceKey(para, tt);
                }                    //遍历表格      
                var tables = doc.Tables;
                foreach (var table in tables)
                {
                    foreach (var row in table.Rows)
                    {
                        foreach (var cell in row.GetTableCells())
                        {
                            foreach (var para in cell.Paragraphs)
                            {
                                ReplaceKey(para, tt);
                            }
                        }
                    }
                }

                FileStream out1 = new FileStream(HttpContext.Current.Server.MapPath("~/simpleTable" + DateTime.Now.Ticks + ".docx"), FileMode.Create);
                doc.Write(out1);
                out1.Close();
            }
        }

        private static void ReplaceKey(XWPFParagraph para, object model)
        {
            string text = para.ParagraphText;
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值