private void bt_txt_to_excel_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
if (folderDialog.ShowDialog() == DialogResult.OK)
{
string selectedFolder = folderDialog.SelectedPath;
// 遍历文件夹中的文件
foreach (string filePath in Directory.GetFiles(selectedFolder))
{
if (Path.GetExtension(filePath).Equals(".txt", StringComparison.OrdinalIgnoreCase))
{
ParseLogFile(filePath);
}
}
}
}
static void ParseLogFile(string filePath)
{
try
{
var fileInfo = new FileInfo(filePath.ToLower().Replace(".txt", ".xlsx"));
if (fileInfo.Exists)
{
try
{
fileInfo.Delete();
}
catch (Exception ex)
{
MessageBox.Show($"删除文件时出错: {ex.Message}");
}
}
using (var package = new ExcelPackage(fileInfo))
{
string id = Guid.NewGuid().ToString();//默认唯一ID
string[] lines = File.ReadAllLines(filePath);
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
// 添加表头
worksheet.Cells[1, 1].Value = "客戶ID";
worksheet.Cells[1, 2].Value = "客戶code";
worksheet.Cells[1, 3].Value = "pcs_code";
worksheet.Cells[1, 4].Value = "版序";
worksheet.Cells[1, 5].Value = "emapping";
int i = 0;
// 在此处添加解析txt的逻辑规则
foreach (string line in lines)
{
int indx = line.IndexOf("sn|cmd90:");
if (indx > 0)
{
string[] datas = line.Substring(indx + 9).Split(';');
worksheet.Cells[2 + i, 1].Value = id;
worksheet.Cells[2 + i, 2].Value = datas[1];
worksheet.Cells[2 + i, 3].Value = datas[2];
worksheet.Cells[2 + i, 4].Value = datas[4].PadLeft(3, '0');
worksheet.Cells[2 + i, 5].Value = "0";
i++;
}
}
package.Save();
MessageBox.Show("导出成功!");
}
}
catch (Exception ex)
{
MessageBox.Show($"解析文件 {filePath} 时出错: {ex.Message}");
}
}
标签:string,档转,worksheet,Cells,filePath,excel,Value,txt
From: https://www.cnblogs.com/xynmw/p/18318158