c# - 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 遇到问题。
解决方案
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
推荐阅读
- azure - 为什么什么都上传不了?- 使用 Xamarin 将信息 blob 上传到 Azure
- json - Google Cloud Vision API : "error code: 3" , "message": "Bad image data."
- python - 解密 .py 代码
- python - 由于两个 IGMPv2 加入消息,每个发送的 UDP 多播消息都会被接收两次。如何避免?
- idl-programming-language - 如何在 IDL 图上添加 '%' 和 '+' 符号?
- dart - 颤动中的下拉按钮不会将值切换到所选值
- mysql - MySQL 中是否有类似的 generate_series 函数?
- android - 如何在 android RecyclerView 中获取列表以在修改其显示内容的活动后更新?
- python - 终端中的python3命令给出没有这样的文件或目录错误
- pandas - 将熊猫 DataFrame 转换为读取文件?