一、将Textbox1中的内容以文本文件的形式保存
引用
using Microsoft.Office.Interop.Excel;
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel
将对话框拖入至窗体
定义公共对象
public Excel.Application oApp;
public Excel._Workbook oWbook;
public Excel._Worksheet owsheet;
public Excel.Range orng;
private void button4_Click(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "文本文件|*.txt";
if(dialog.ShowDialog() == DialogResult.OK)
{
// 文件名
string fileName = dialog.FileName;
// 创建文件,准备写入
FileStream fs = File.Open(fileName,
FileMode.Create,
FileAccess.Write);
StreamWriter wr = new StreamWriter(fs);
// 逐行将textBox1的内容写入到文件中
foreach (string line in textcontent.Lines)
{
wr.WriteLine(line);
}
// 关闭文件
wr.Flush();
wr.Close();
fs.Close();
}
}
二、将文本文件转换为EXCEL表格
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog exceldat=new OpenFileDialog();
exceldat.Filter = "Text File(*.txt)|*.txt";
if(exceldat.ShowDialog() != DialogResult.OK)
{
return;
}
string pathname = exceldat.FileName;
StreamReader sr = new StreamReader(pathname);
string strLine=sr.ReadLine();
int rowNum = 1;
object missing = System.Reflection.Missing.Value;
Excel.Application app = new Excel.Application();
app.Application.Workbooks.Add(true);
Workbook book = (Workbook)app.ActiveWorkbook;
Worksheet sheet = (Worksheet)book.ActiveSheet;
while (!string.IsNullOrEmpty(strLine))
{
string[] tempArr;
tempArr = strLine.Split(',');
for(int k = 1; k <= tempArr.Length; k++)
{
sheet.Cells[rowNum, k] = tempArr[k - 1];
}
strLine = sr.ReadLine();
rowNum++;
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel Workbook(*.xlsx)|*.xlsx";
//if (saveFileDialog.ShowDialog() != DialogResult.OK)
//{
// book.Save();
// //book.SaveAs(saveFileDialog.FileName);
//}
book.Close();
app.Quit();
MessageBox.Show("转化成功!");
}
}
}
将Textbox内容以文本文件形式保存
打开文本文件
将文本文件转换为Excel文件