You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用无授权库创建并写入.doc文件的技术问题求助

解决方案:创建并写入旧版Word(.doc)文件

方案一:修正NPOI.HWPF的使用方式

NPOI.HWPF依赖合法的Word二进制文档结构,完全空白的自定义.doc文件会导致解析错误。你需要使用Microsoft Word手动生成的标准空白.doc文件作为模板,而非自行创建的空文件。

修正后的代码

using NPOI.HWPF;
using NPOI.HWPF.UserModel;
using System.IO;

namespace ConsoleApp4;

class Program
{
    static void Main(string[] args)
    {
        string templatePath = "/home/evgeniy/test/standard-blank.doc"; // Word生成的标准空白模板
        string outputPath = "/home/evgeniy/test/newDoc.doc";
        string content = "测试文本\n支持多行内容\n任意长度都可以";

        using (var fs = new FileStream(templatePath, FileMode.Open, FileAccess.Read))
        {
            using (var doc = new HWPFDocument(fs))
            {
                Range range = doc.GetRange();
                // 清空模板原有内容(按需选择)
                range.Delete();
                // 插入目标内容
                range.InsertAfter(content);

                using (var ofs = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
                {
                    doc.Write(ofs);
                }
            }
        }
    }
}

关键说明

  • 模板文件必须是Word直接保存的空白.doc(打开Word后直接保存即可,默认包含一个空白段落),这种文件带有完整的Word二进制结构,NPOI可以正常解析。
  • 原有报错A property claimed to end (29) before start!是因为自定义空文件缺少必要的文档属性段,标准模板可以彻底解决这个问题。

方案二:使用FreeSpire.Doc直接创建.doc文件

如果不想依赖模板,推荐使用FreeSpire.Doc(非商业场景免费无授权限制),它支持直接创建旧版.doc文件,无需模板。

代码示例

先通过NuGet安装FreeSpire.Doc,然后使用以下代码:

using Spire.Doc;
using Spire.Doc.Documents;

namespace ConsoleApp4;

class Program
{
    static void Main(string[] args)
    {
        string outputPath = "/home/evgeniy/test/newDoc.doc";
        string content = "这是任意长度的文本,支持基础格式\n比如设置段落对齐、字体样式等";

        // 新建空白.doc文档
        Document doc = new Document();
        // 添加章节和段落
        Section section = doc.AddSection();
        Paragraph paragraph = section.AddParagraph();
        // 写入内容
        paragraph.AppendText(content);

        // 保存为.doc格式
        doc.SaveToFile(outputPath, FileFormat.Doc);
        doc.Close();
    }
}

优势

  • 无需依赖外部模板,直接生成合法的.doc文件。
  • 支持更多格式设置(如字体、段落对齐、列表等),比NPOI更易用。

内容的提问来源于stack exchange,提问作者ev.shevnun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 02:47:18