c# 将指定文件名和路径的txt文档内容读出来并写到Excel中—winform程序

发布时间 2023-06-13 14:44:53作者: 羽小兮

使用 C# 中的 `System.IO` 和 `Microsoft.Office.Interop.Excel` 库来实现读取文本文件和写入 Excel 文件。

以下是一个示例代码:

 1 using System;
 2 using System.IO;
 3 using System.Windows.Forms;
 4 using Microsoft.Office.Interop.Excel;
 5 
 6 namespace WinFormDemo
 7 {
 8     public partial class Form1 : Form
 9     {
10         public Form1()
11         {
12             InitializeComponent();
13         }
14 
15         private void button1_Click(object sender, EventArgs e)
16         {
17             // 选择要读取的文本文件
18             OpenFileDialog openFileDialog = new OpenFileDialog();
19             openFileDialog.Filter = "Text Files (*.txt)|*.txt";
20             if (openFileDialog.ShowDialog() != DialogResult.OK)
21             {
22                 return;
23             }
24             string filePath = openFileDialog.FileName;
25 
26             // 读取文本文件内容
27             string textContent = File.ReadAllText(filePath);
28 
29             // 创建 Excel 应用程序对象
30             var excelApp = new Application
31             {
32                 Visible = false // 设置不显示 Excel 窗口
33             };
34             try
35             {
36                 // 创建一个新的工作簿
37                 var workbook = excelApp.Workbooks.Add(Type.Missing);
38 
39                 // 获取第一个工作表
40                 var worksheet = (Worksheet)workbook.Worksheets[1];
41 
42                 // 根据换行符将文本内容分割成行
43                 var lines = textContent.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
44 
45                 // 将文本内容写入工作表中
46                 for (int i = 0; i < lines.Length; i++)
47                 {
48                     worksheet.Cells[i + 1, 1] = lines[i];
49                 }
50 
51                 // 保存 Excel 文件
52                 SaveFileDialog saveFileDialog = new SaveFileDialog();
53                 saveFileDialog.Filter = "Excel Workbook (*.xlsx)|*.xlsx";
54                 if (saveFileDialog.ShowDialog() == DialogResult.OK)
55                 {
56                     workbook.SaveAs(saveFileDialog.FileName);
57                 }
58 
59                 // 关闭工作簿和 Excel 应用程序
60                 workbook.Close();
61                 excelApp.Quit();
62             }
63             catch (Exception ex)
64             {
65                 // 处理异常
66                 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
67             }
68         }
69     }
70 }

 

此代码将从打开文件对话框中选择的文本文件读取内容,并使用换行符分割成多行,然后将其写入到 Excel 工作表的第一列中。最后将 Excel 文件保存在另一个文件对话框中指定的位置。请注意,这里使用了 `SaveAs` 方法而不是 `Save` 方法,因为我们要将 .txt 文本文件转换成 .xlsx Excel 文件格式。