当前位置: 首页 > news >正文

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=================");}}}

http://www.xdnf.cn/news/100225.html

相关文章:

  • 【论文阅读】Dual-branch Cross-Patch Attention Learning for Group Affect Recognition
  • Tkinter:Python 3官方轻量级GUI库
  • 常见的五种权限管理模型
  • 用交换机连接两台电脑,电脑A读取/写电脑B的数据
  • openGauss数据库:起源、特性与对比分析
  • CSS内边距、外边距、边框
  • 【C/C++】插件机制:基于工厂函数的动态插件加载
  • 【多线程】二、pthread库 线程控制 线程分离 __thread关键字 线程库封装
  • skynet.cluster 库函数应用
  • update方法
  • Kafka 保证多分区的全局顺序性的设计方案和具体实现
  • 接口访问数据库报错问题记录
  • Java多线程的暗号密码:5分钟掌握wait/notify
  • 大模型框架技术演进与全栈实践指南
  • 57、Spring Boot 最佳实践
  • 模板方法模式:定义算法骨架的设计模式
  • 图文结合 - 光伏系统产品设计PRD文档 -(慧哥)慧知开源充电桩平台
  • docker学习笔记5-docker中启动Mysql的最佳实践
  • SQL技术终极指南:从内核原理到超大规模应用
  • 4.23刷题记录(栈与队列专题)
  • devops自动化容器化部署
  • 【人工智能】解锁 AI 潜能:DeepSeek 大模型迁移学习与特定领域微调的实践
  • MCP 协议:AI 时代的 “USB-C” 革命——从接口统一到生态重构的技术哲学
  • 硬核解析:整车行驶阻力系数插值计算与滑行阻力分解方法论
  • vue项目打包后点击dist下面index.html(无法访问您的文件该文件可能已被移至别处、修改或删除。ERR_FILE_NOT_FOUND)比如若依
  • 金仓读写分离集群修改IP
  • 从性能到安全:大型网站系统架构演化的 13 个核心维度
  • Qt案例 使用QFtpServerLib开源库实现Qt软件搭建FTP服务器,使用QFTP模块访问FTP服务器
  • C语言中小写字母转大写字母
  • 数据通信学习笔记之OSPF的基础术语