C#语言实现PDF转Excel
- 实现效果
- 第三方库
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=================");}}}