using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using Microsoft.Office.Interop.Excel; using System.Reflection; namespace ReadTextToExcel { public partial class FrmReadTxtToExcel : Form { public FrmReadTxtToExcel() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.ofdRead.ShowDialog(); this.tbxReadFile.Text = this.ofdRead.FileName; } private void FrmReadTxtToExcel_Load(object sender, EventArgs e) { } private void btnWrite_Click(object sender, EventArgs e) { this.ofdWrite.ShowDialog(); this.tbxWriteFile.Text = this.ofdWrite.FileName; } private void btnOperate_Click(object sender, EventArgs e) { FileStream fs = new FileStream(this.tbxReadFile.Text.ToString(), FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs,System.Text.Encoding.GetEncoding("gb2312")); Microsoft.Office.Interop.Excel.Application xApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); xApp.Visible = true; //得到WorkBook对象, 可以用两种方式之一: 下面的是打开已有的文件 Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks._Open(this.tbxWriteFile.Text.ToString(), Missing.Value, Missing.Value, Missing.Value, Missing.Value , Missing.Value, Missing.Value, Missing.Value, Missing.Value , Missing.Value, Missing.Value, Missing.Value, Missing.Value); //xBook=xApp.Workbooks.Add(Missing.Value);//新建文件的代码 //指定要操作的Sheet,如下两种方式 Microsoft.Office.Interop.Excel.Worksheet xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1]; //Excel.Worksheet xSheet=(Excel.Worksheet)xApp.ActiveSheet; sr.BaseStream.Seek(0, SeekOrigin.Begin); //定位操作点,begin 是一个参考点 sr.BaseStream.Seek(0, SeekOrigin.Begin); //读一下,看看文件内有没有内容,为下一步循环 提供判断依据 string str = sr.ReadLine();//如果 文件有内容 int index = 1; while (str != null) { //输出字符串,str 在上面已经定义了 读入一行字符 this.textBox3.Text = textBox3.Text.ToString() + str; //写入数据 Microsoft.Office.Interop.Excel.Range rng3 = xSheet.get_Range(Convert.ToString("A"+index), Missing.Value); rng3.Value2 = str; //rng3.Interior.ColorIndex = 6; //设置Range的背景色 index++; str = sr.ReadLine(); } //C#读取TXT文件之后关闭文件,注意顺序,先对文件内部进行关闭,然后才是文件 sr.Close(); fs.Close(); //保存方式一:保存WorkBook //xBook.SaveAs(this.textBox2.Text.ToString(), //Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, //Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, //Missing.Value, Missing.Value); //保存方式二 xBook.Save(); xSheet = null; xBook = null; xApp.Quit(); //这一句是非常重要的,否则Excel对象不能从内存中退出 xApp = null; } private void btnExit_Click(object sender, EventArgs e) { this.Dispose(); System.Windows.Forms.Application.Exit(); } } }