[VS_C#实战案例](1)批量提取文件夹内txt内容生成excel表格
个人边学习边开发的日常总结,发布在此与各位交流、共同进步。
语言:c#
软件:visual studio
实现功能:提取指定文件夹内批量的txt文件;根据user给定字符串,提取该字符串后数值;并将提取内容生成到excel并排序。
适用环境:批量提取大量log文件内的指定数值,形成excel表格,方便对该项数值进行处理。
代码分功能如下:
1、点击按钮1,打开文件夹选择文件夹路径
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog1 = new FolderBrowserDialog();//定义打开文件夹函数
if (dialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dialog1.SelectedPath;//把所选文件夹路径赋值给textbox1
}
}
2、点击按钮2,合并文件夹内txt文件,根据user输入的字符串,从合并后文件提取字符串生成excel
private void button2_Click(object sender, EventArgs e)
{
//定义所选路径
string path = textBox1.Text;
//文件夹内多个txt文件合并
var myfiles = Directory.GetFiles(path, "*.txt");
List<String> contents = new List<String>();
foreach(var ff in myfiles)
{
contents.AddRange(File.ReadAllLines(ff));
}
File.WriteAllLines(textBox1.Text + "/acombine.txt", contents.ToArray()); //合并后在文件夹路径下生成txt文件
string mypath = textBox1.Text + @"\acombine.txt"; //定义生成后的txt文件的路径
Thread.Sleep(1000); 延时1000ms
//读取文档
StreamReader sr = new StreamReader(mypath, Encoding.Default);
string strLine = sr.ReadLine();
int rowNum = 1;
object missing = System.Reflection.Missing.Value;
app.Application.Workbooks.Add(true);
Workbook book = (Workbook)app.ActiveWorkbook;
Worksheet sheet = (Worksheet)book.ActiveSheet;
Range r = sheet.get_Range("A1", "E1");
//获取行数
object[,] objectData = new object[65535, 5];
while (!string.IsNullOrEmpty(strLine))
{
string[] tempArr;
tempArr = strLine.Split('\n');//以换行分割数组
/*以字符串分割数组
string ss = textBox2.Text;
char[] cc = ss.ToCharArray();
tempArr = strLine.Split(cc);
*/
objectData[0, 1] = textBox2.Text.Replace("=", "").Replace(":", "");//object[0,0]代表row 1 ,colum 1
for (int k = 1; k <= tempArr.Length; k++)
{
if(tempArr[k-1].Contains(textBox2.Text)==true)
{
objectData[rowNum, 0] = rowNum;
objectData[rowNum, 1] = tempArr[k - 1].Replace(textBox2.Text, "").Replace(";", "").Replace(":", "").Replace("=", "");//去除多余不需要的字符串
rowNum++;
}
else
{
}
}
strLine = sr.ReadLine();
}
Thread.Sleep(1000);
r = r.get_Resize(65535, 5);
r.Value2 = objectData;
//r.EntireColumn.AutoFit(); excel表格自动size
// excelRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; 文本水平居中方式
r.HorizontalAlignment = XlHAlign.xlHAlignCenter;
//保存excel文件
string name = mypath.Replace(".txt","");
try
{
book.SaveCopyAs(name + ".xlsx");//保存为xlsx格式
MessageBox.Show("转化成功!");
}
catch(Exception)
{
MessageBox.Show("Fail");
}
//关闭文件
book.Close(false, missing, missing);
//退出excel
sr.Close();//停止占用
Thread.Sleep(500);
Process.Start(name + ".xlsx");//自动打开生成后的excel文件
}
3、所用到的命名空间
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;