- 實現效果
- 第三方庫
ClosedXML
iTextSharp
- 實現源碼
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.Text.RegularExpressions;
using ClosedXML.Excel;namespace PdfToExcel_winform
{public partial class MainForm : Form{public MainForm(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){DateTime specificDate = new DateTime(9999, 3, 15); // 試用截至日期DateTime currentDate = DateTime.Now; // 獲取當前日期和時間if (specificDate < currentDate){AddTextAndScroll("******************************************************************************"); AddTextAndScroll("==========軟件試用已到期,請聯系軟件開發者授權續期==========");AddTextAndScroll("******************************************************************************");button1.Enabled = false;}}private void textBox1_TextChanged(object sender, EventArgs e){AddTextAndScroll("=================程序開始執行,START=================");string pdfPath = textBox1.Text;using (PdfReader reader = new PdfReader(pdfPath)){StringBuilder text = new StringBuilder();for (int i = 1; i <= reader.NumberOfPages; i++){text.Append(PdfTextExtractor.GetTextFromPage(reader, i));}// richTextBox1.Text = text.ToString();AddTextAndScroll("文件讀取完成,原始文件信息:\n" + text.ToString());ReadLine(text.ToString(), pdfPath);}}private void button1_Click(object sender, EventArgs e){if (openFileDialog1.ShowDialog() == DialogResult.OK){// 獲取選擇的文件路徑string selectedFilePath = openFileDialog1.FileName;// 處理文件路徑,例如顯示在文本框中或標簽中textBox1.Text = selectedFilePath;}}private void richTextBox1_TextChanged(object sender, EventArgs e){// richTextBox1.ScrollToCaret();}private void AddTextAndScroll(string text){// 添加文本到RichTextBoxrichTextBox1.AppendText(text + Environment.NewLine);// 滾動到RichTextBox的最后richTextBox1.ScrollToCaret();}private void ReadLine(string text, string path){List<Dictionary<string, string>> dataDictionaryList = new List<Dictionary<string, string>>();using (StringReader reader = new StringReader(text.ToString())){string line, line1;while ((line = reader.ReadLine()) != null){if (line.StartsWith(" ") && line.Length > 5){try{// AddTextAndScroll("11111:" + line);line = Regex.Replace(line, @"\s+", " ");string[] split = line.Trim().Split(" ");AddTextAndScroll("按行提取有用文件內容:" + string.Join(" ", split));line1 = reader.ReadLine();line1 = Regex.Replace(line1, @"\s+", " ");string[] split1 = line1.Trim().Split(" ");AddTextAndScroll("按行提取有用文件內容:" + string.Join(" ", split1));string total = split1.Last();split1 = split1.Take(split1.Length - 1).ToArray();Dictionary<string, string> dataDictionary = new Dictionary<string, string>();// AddTextAndScroll(" 長度=====:" + split.Length);dataDictionary.Add("no", split[0]);dataDictionary.Add("sum", split[1]);dataDictionary.Add("desc", string.Join(" ", split1));dataDictionary.Add("xh", split[3]);dataDictionary.Add("price", split[5]);dataDictionary.Add("total", total);AddTextAndScroll("行數據處理完成" );dataDictionaryList.Add(dataDictionary);}catch (Exception ex){AddTextAndScroll("程序出錯:" + ex.Message);}}}//調用excel處理邏輯WriteExcel(dataDictionaryList, path);}}private void WriteExcel(List<Dictionary<string, string>> dataDictionaryList, string path){string fileName = System.IO.Path.GetFileNameWithoutExtension(path);string directoryPath = System.IO.Path.GetDirectoryName(path);string excelPath = System.IO.Path.Combine(directoryPath, fileName + ".xlsx");AddTextAndScroll("Excel文件創建完成,文件路徑為:" + excelPath);// 創建一個新的Excel文件using (var workbook = new XLWorkbook()){// 添加一個工作表var worksheet = workbook.AddWorksheet("Sheet1");// 數據填充worksheet.Cell(1, 1).Value = "序號";worksheet.Cell(1, 2).Value = "數量";worksheet.Cell(1, 3).Value = "描述";worksheet.Cell(1, 4).Value = "型號";worksheet.Cell(1, 5).Value = "單價";worksheet.Cell(1, 6).Value = "金額";var dataList = dataDictionaryList.ToArray();for (var i = 0; i < dataList.Length; i++) {//worksheet.Cell(i + 2, 1).Value = Convert.ToInt16(dataDictionaryList[i]["no"]);//worksheet.Cell(i + 2, 2).Value = Convert.ToDouble(dataDictionaryList[i]["sum"]);//worksheet.Cell(i + 2, 3).Value = dataDictionaryList[i]["desc"];//worksheet.Cell(i + 2, 4).Value = dataDictionaryList[i]["xh"];//worksheet.Cell(i + 2, 5).Value = dataDictionaryList[i]["price"];//worksheet.Cell(i + 2, 6).Value = Convert.ToDecimal(dataDictionaryList[i]["total"]);worksheet.Cell(i + 2, 1).Value = dataDictionaryList[i]["no"];worksheet.Cell(i + 2, 2).Value = dataDictionaryList[i]["sum"];worksheet.Cell(i + 2, 3).Value = dataDictionaryList[i]["desc"];worksheet.Cell(i + 2, 4).Value = dataDictionaryList[i]["xh"];worksheet.Cell(i + 2, 5).Value = dataDictionaryList[i]["price"];worksheet.Cell(i + 2, 6).Value = dataDictionaryList[i]["total"];AddTextAndScroll($"第{i+1}行數據寫入Excel表");}AddTextAndScroll("設置Excel表格列寬自適用");worksheet.Columns().AdjustToContents();worksheet.Column(1).Width = 7;// 保存Excel文件workbook.SaveAs(excelPath);}AddTextAndScroll("開始保存Excel文件");AddTextAndScroll("Excel文件保存完成,文件路徑為:" + excelPath);AddTextAndScroll("=================程序執行結束,END=================");}}}