【问题标题】:c# copy from text file to word documentc#从文本文件复制到word文档
【发布时间】:2018-09-04 10:25:16
【问题描述】:

我想将数据从文本文件复制到 word 文件。我已经尝试过使用Interop 使用string arrayStringBuilderStreamReader 等不同的替代方案,效果很好,但需要太多时间。如果有人能给我推荐一个更好的,那将非常感激。在网上翻了很多表格,都找不到。

仅供参考:我的文本文件包含超过 1,00,000 行。

这是我尝试过的一种:

string[] lines = File.ReadAllLines(path); //path is text file path
var doc = new MSWord.Document();

foreach (string lin in lines)
{
    doc.Content.Text += lin.ToString();
}

doc.Save();

嗯,这很好用,但需要很多时间,有时还会引发如下错误:

未处理的异常:System.Runtime.InteropServices.COMException:Word 遇到问题。

【问题讨论】:

  • 为什么不File.ReadAllText 然后删除foreach 循环?这比在循环中连接字符串要“便宜”得多。 doc.Content.Text = File.ReadAllText(path);
  • 您是否调查过导致异常的原因?例如 - 您尝试附加的字符串中是否有不寻常的字符? Igor 的解决方案会节省时间 - 但如果异常是由于您的文本文件的内容引起的 - 那么它仍然可能发生。
  • @lgor:是的,这实际上会做得更好,但我仍然需要超过 15 分钟的时间。
  • 我建议尝试Range.ImportFragment
  • 不使用 File 方法读取文件 - 你能用 MSWord 文档打开文本文件然后另存为 word 文档吗?

标签: c# ms-word text-files winforms-interop


【解决方案1】:
    static void Main(string[] args)
    {
        Word.Application wordApp = new Word.Application();
        Word.Document wordDoc = wordApp.Documents.Add();
        Stopwatch sw = Stopwatch.StartNew();
        System.Console.WriteLine("Starting");
        string path = @"C:\";
        StringBuilder stringBuilder = new StringBuilder();
        using (FileStream fs = File.Open(path + "\\big.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (BufferedStream bs = new BufferedStream(fs))
        using (StreamReader sr = new StreamReader(bs))
        {
            wordDoc.Content.Text = sr.ReadToEnd();
            wordDoc.SaveAs("big.docx");
        }
        sw.Stop();
        System.Console.WriteLine($"Complete Time :{sw.ElapsedMilliseconds}");
        System.Console.ReadKey();
    }

输出:

Starting
Complete Time :5556

或者你可以使用并行:

    using (StreamReader sr = new StreamReader(bs))
    {
        Parallel.ForEach(sr.ReadToEnd(), i=>
        {
            stringBuilder.Append(i);
        });
        wordDoc.Content.Text = stringBuilder.ToString();
        wordDoc.SaveAs(path + "\\big3.docx");
    }

输出:

Starting
Complete Time :2587

【讨论】:

  • 这似乎不是在写入 Word 文档,这是 OP 的特定查询。
  • @OMansAK:我正在将数据从文本文件复制到 word 文件。
  • @AshishSrivastava 已修复
  • @AshishSrivastava 也许你可以使用并行来提高速度
  • 字符串生成器不是线程安全的,即使它使用并行也会无序写入。
【解决方案2】:

Microsoft Word 可以读取文本文件 - 那么为什么不将文本文件读入 Interop Word 文档,然后使用其中一种 SaveAs 方法进行转换。

我测试了一个 34Mb、1000000 行的文本文件 - 结果是一个 22Mb 的 DOCX 文件:

MSWord.Application appAC = new MSWord.Application();
MSWord.Document doc = appAC.Documents.Open("TestRead.txt");
doc.SaveAs2(FileName:"TestSave", FileFormat:WdSaveFormat.wdFormatDocumentDefault);
doc.Close();
appAC.Quit();

请注意,Microsoft 声明最大文档大小为 32MB - 文本文件超过了这个值,但生成的 DOCX 文件更小 - 您的异常可能与最终文件的大小有关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多