Winform小工具:.txt檔轉excel檔

txtspring發表於2024-07-23
    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("barcode:");
                    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}");
        }
    }

相關文章