首页 > 解决方案 > c#从文本文件复制到word文档

问题描述

我想将数据从文本文件复制到word文件。我已经尝试过使用不同的替代方法,例如string array,StringBuilder并且StreamReader使用Interop效果很好,但它需要太多时间。如果有人能给我推荐一个更好的,那将非常感激。网上查了很多表格,没找到。

仅供参考:我的文本文件包含超过 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 遇到问题。

标签: c#ms-wordtext-fileswinforms-interop

解决方案


    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

或者您可以使用 Parallel :

    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

推荐阅读