C#从文本文件复制到Word文档

时间:2018-09-04 10:25:17

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

我想将数据从文本文件复制到Word文件。我已经使用string arrayStringBuilderStreamReaderInterop等不同的替代方法进行了尝试,虽然效果很好,但是花费太多时间。如果有人可以给我更好的建议,那将是非常感谢。遍历了网络上的许多表格,但找不到。

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

2 个答案:

答案 0 :(得分:2)

{"code":405000,"message":"The request method is not supported for the requested resource."}

输出:

    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();
    }

或者您可以使用Parallel:

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");
    }

答案 1 :(得分:1)

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文件更小-您的例外情况可能与最终文件的大小有关。

相关问题