WPF编程excel表格操作

WPF编程excel表格操作

  • 摘要
  • NPOI安装
  • 封装代码
  • 测试代码

摘要

Excel操作几种方式

  • 使用开源库NPOI(常用,操作丰富)
  • 使用Microsoft.Office.Interop.Excel COM组件(兼容性问题)
  • 使用OpenXml(效率高)
  • 使用OleDb(过时)

NPOI安装

在这里插入图片描述

封装代码

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;using NPOI.SS.Util;
using NPOI.SS.UserModel;    
using NPOI.XSSF.UserModel;  // 对于.xlsx文件
using NPOI.HSSF.UserModel;  // 对于.xls文件namespace GasAlarmTestTool
{internal class ExcelTools{/// <summary>/// 创建Excel表/// </summary>/// <param name="filePath"></param>/// <param name="dataTable"></param>public void CreateNewExcel(string filePath, DataTable dataTable){IWorkbook workbook;if (filePath.EndsWith(".xlsx")){workbook = new XSSFWorkbook(); // 创建 .xlsx 文件}else{workbook = new HSSFWorkbook(); // 创建 .xls 文件}var sheet = workbook.CreateSheet("Sheet1");// 写入表头var headerRow = sheet.CreateRow(0);for (int i = 0; i < dataTable.Columns.Count; i++){headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);}// 写入数据for (int i = 0; i < dataTable.Rows.Count; i++){var dataRow = sheet.CreateRow(i + 1);for (int j = 0; j < dataTable.Columns.Count; j++){dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());}}SetUniformColumnWidth(sheet, 20);   // 默认统一列宽20// 保存文件using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write)){workbook.Write(stream);}}/// <summary>/// 追加Excel表/// 追加数据时,可以定位到现有数据的末尾,创建新行并写入。/// </summary>/// <param name="filePath"></param>/// <param name="dataTable"></param>public void AppendDataToExistingExcel(string filePath, DataTable dataTable){IWorkbook workbook;using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)){workbook = filePath.EndsWith(".xlsx") ? (IWorkbook)new XSSFWorkbook(stream) : new HSSFWorkbook(stream);}var sheet = workbook.GetSheetAt(0);int lastRowNum = sheet.LastRowNum;for (int i = 0; i < dataTable.Rows.Count; i++){var dataRow = sheet.CreateRow(lastRowNum + i + 1);for (int j = 0; j < dataTable.Columns.Count; j++){dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());}}using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Write)){workbook.Write(stream);}}/// <summary>/// 查找指定列是否存在item项/// </summary>/// <param name="filePath"></param>/// <param name="item"></param>/// <param name="colIndex"></param>/// <returns></returns>public bool SearchColumnExitsItem(string filePath, string item, int colIndex){IWorkbook workbook;using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)){workbook = filePath.EndsWith(".xlsx") ? (IWorkbook)new XSSFWorkbook(stream) : new HSSFWorkbook(stream);}var sheet = workbook.GetSheetAt(0);// 遍历每一行for (int row = 0; row <= sheet.LastRowNum; row++){IRow currentRow = sheet.GetRow(row);if (currentRow != null){// 遍历每一列for (int column = 0; column < currentRow.LastCellNum; column++){ ICell currentCell = currentRow.GetCell(column);var cellValue = currentCell.ToString();if ((column == colIndex) && (cellValue == item)){return true;}}}}     return false;}/// <summary>/// 设置列宽/// </summary>/// <param name="workbook"></param>/// <param name="sheetIndex"></param>/// <param name="columnIndex"></param>public void SetColumnWidth(IWorkbook workbook, int sheetIndex, int columnIndex){var sheet = workbook.GetSheetAt(sheetIndex);// 设置列宽(单位是 1/256 字符宽度)sheet.SetColumnWidth(columnIndex, 20 * 256); // 设置第1列宽度为20}/// <summary>/// 设置行高/// </summary>/// <param name="workbook"></param>/// <param name="sheetIndex"></param>/// <param name="rowIndex"></param>public void SetColumnRowHeight(IWorkbook workbook, int sheetIndex, int rowIndex){var sheet = workbook.GetSheetAt(sheetIndex);// 设置行高(单位是点数)var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);row.HeightInPoints = 25; // 设置行高为25点}/// <summary>/// 同时设置列宽和行高/// </summary>/// <param name="workbook"></param>/// <param name="sheetIndex"></param>/// <param name="columnIndex"></param>/// <param name="rowIndex"></param>/// <param name="width"></param>/// <param name="height"></param>public void SetColumnWidthAndRowHeight(IWorkbook workbook, int sheetIndex, int columnIndex, int rowIndex, int width, int height){var sheet = workbook.GetSheetAt(sheetIndex);// 设置列宽(单位是1/256字符宽度)sheet.SetColumnWidth(columnIndex, width * 256); // 设置第1列宽度为 20 var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex); row.HeightInPoints = height; // 25}/// <summary>/// 设置统一行高/// </summary>/// <param name="sheet"></param>/// <param name="heightInPoints"></param>public void SetUniformRowHeight(ISheet sheet, float heightInPoints){for (int i = 0; i < sheet.LastRowNum; i++){ var row = sheet.GetRow(i) ?? sheet.CreateRow(i);row.HeightInPoints = heightInPoints;}}/// <summary>/// 设置统一列宽/// </summary>/// <param name="sheet"></param>/// <param name="widthInCharacters"></param>public void SetUniformColumnWidth(ISheet sheet, int widthInCharacters){for (int i = 0; i < sheet.GetRow(0).LastCellNum; i++) // 以第一行的单元格数量为列数{sheet.SetColumnWidth(i, widthInCharacters * 256); // 设置列宽}}/// <summary>/// 设置统一行高和列宽/// </summary>/// <param name="sheet"></param>/// <param name="rowHeightInPoints"></param>/// <param name="columnWidthCharacters"></param>public void SetUniformRowHeightAndColumnWidth(ISheet sheet, float rowHeightInPoints, int columnWidthCharacters){SetUniformRowHeight(sheet, rowHeightInPoints);SetUniformColumnWidth(sheet, columnWidthCharacters);}/// <summary>/// 合并单元格可以通过 CellRangeAddress 设置,需要定义起始和结束的行列。/// </summary>/// <param name="workbook"></param>/// <param name="sheetIndex"></param>/// <param name="firstRow"></param>/// <param name="lastRow"></param>/// <param name="firstCol"></param>/// <param name="lastCol"></param>public void MergeCells(IWorkbook workbook, int sheetIndex, int firstRow, int lastRow, int firstCol, int lastCol){var sheet = workbook.GetSheetAt(sheetIndex);// 合并单元格var cellRangeAddress = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);sheet.AddMergedRegion(cellRangeAddress);// 可以对合并后的单元格设置样式var cell = sheet.GetRow(firstRow).GetCell(firstCol) ?? sheet.GetRow(firstRow).CreateCell(firstCol);var style = workbook.CreateCellStyle();style.Alignment = HorizontalAlignment.Center;cell.CellStyle = style; }public void SetCellStyle(IWorkbook workbook, int sheetIndex, int rowIndex, int colIndex){var sheet = workbook.GetSheetAt(sheetIndex);var cell = sheet.GetRow(rowIndex).GetCell(colIndex) ?? sheet.GetRow(rowIndex).CreateCell(colIndex);var style = workbook.CreateCellStyle();// 设置字体var font = workbook.CreateFont();font.FontHeightInPoints = 1;font.FontName = "Arial";font.IsBold = true;style.SetFont(font);// 设置边框style.BorderBottom = BorderStyle.Thin;style.BorderLeft = BorderStyle.Thin;style.BorderRight = BorderStyle.Thin;style.BorderTop = BorderStyle.Thin;// 设置背景颜色style.FillForegroundColor = IndexedColors.LightBlue.Index;style.FillPattern = FillPattern.SolidForeground;cell.CellStyle = style;cell.SetCellValue("示例文本内容");}}
}

测试代码

private ExcelTools excel = new ExcelTools();
string excelFileName = Properties.Settings.Default.SavePath + "/燃气报警器数据表格.xlsx";// TODO: 生成保存数据
DataTable dt = new DataTable();
dt.Columns.Add("设备UUID", typeof(string));
dt.Columns.Add("SIM卡号", typeof(string));
dt.Columns.Add("设备型号", typeof(string));
dt.Columns.Add("网络型号", typeof(string));
dt.Columns.Add("生产日期", typeof(string));DataRow dr = dt.NewRow();
dr["设备UUID"] = "2021886000001";
dr["SIM卡号"] = "86452215642112345675";
dr["设备型号"] = "单甲烷";
dr["网络型号"] = "NB-IoT";
dr["生产日期"] = DateTime.Now.ToString();
dt.Rows.Add(dr);if (excelFileName.EndsWith(".xls") || excelFileName.EndsWith(".xlsx"))
{if (!File.Exists(excelFileName)){// TODO: 文件不存在创建文件excel.CreateNewExcel(excelFileName, dt);}else{// TODO: 将IMEI号写入个Excel表格,若已经写入过则不再写入,防止重复写入if (excel.SearchColumnExitsItem(excelFileName, label_imei.Content.ToString(), 0) == false){excel.AppendDataToExistingExcel(excelFileName, dt);}}
}
else
{MessageBox.Show("请先设置表格文件保存!");
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/64535.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

tcp_rcv_synsent_state_process函数

tcp_rcv_synsent_state_process 是 Linux Kernel 中用于处理 TCP 连接在 SYN-SENT 状态下接收到报文的函数。这个函数在 TCP 三次握手阶段起到了至关重要的作用,处理了在客户端发送 SYN 请求之后收到服务器响应报文的各种情况。 以下是这个函数的解读和剖析: int tcp_rcv_sy…

音视频采集推流时间戳记录方案

音视频同步更多文章 深入理解音视频pts&#xff0c;dts&#xff0c;time_base以及时间数学公式_视频pts计算-CSDN博客 ffplay音视频同步分析_ffplay 音视频同步-CSDN博客 音视频采集打时间戳设计 实时音视频数据的采集和处理场景。具体来说: 采集阶段: 在音视频数据采集过…

Spark Runtime Filter

Runtime Filter 参考链接&#xff1a; https://docs.google.com/document/d/16IEuyLeQlubQkH8YuVuXWKo2-grVIoDJqQpHZrE7q04/edit?tabt.0https://www.modb.pro/db/557718https://issues.apache.org/jira/browse/SPARK-32268https://github.com/apache/spark/pull/35789https…

从0入门自主空中机器人-1【课程介绍】

关于本课程&#xff1a; 本次课程是一套面向对自主空中机器人感兴趣的学生、爱好者、相关从业人员的免费课程&#xff0c;包含了从硬件组装、机载电脑环境设置、代码部署、实机实验等全套详细流程&#xff0c;带你从0开始&#xff0c;组装属于自己的自主无人机&#xff0c;并让…

专业140+总分410+南京大学851信号与系统考研经验南大电子信息通信集成电路,真题,大纲。参考书。

本人本科中等211&#xff0c;离保送本校差一点&#xff0c;考研前纠结本校还是追求更高目标&#xff0c;和家人聊了自己的想法&#xff0c;感谢父母对我的支持&#xff0c;坚定报考南大的目标&#xff0c;最终专业851信号与系统140&#xff0c;总分410顺利被南京大学录取&#…

【C++】初识C++之C语言加入光荣的进化(上)

写在前面 本篇笔记作为C的开篇笔记&#xff0c;主要是讲解C关键字(C98)连带一点点(C11)的知识。掌握的C新语法新特性&#xff0c;当然C是兼容C的&#xff0c;我们学习C的那套在C中也是受用。 ps:点我跳转下集 文章目录 写在前面一、命名空间域1.1、命名空间域的定义与使用1.2…

CGAL windows 安装教程

1.下载源代码 CGAL官网下载https://github.com/CGAL/cgal/releases 2.下载boost库 BOOST官网下载https://www.boost.org/ 3.下载 GMP and MPFR 4.配置VS2022 头文件&#xff1a; 库路径 做完以上步骤&#xff0c;可以使用CGAL了&#xff01;

从0入门自主空中机器人-2-2【无人机硬件选型-PX4篇】

1. 常用资料以及官方网站 无人机飞控PX4用户使用手册&#xff08;无人机基本设置、地面站使用教程、软硬件搭建等&#xff09;&#xff1a;https://docs.px4.io/main/en/ PX4固件开源地址&#xff1a;https://github.com/PX4/PX4-Autopilot 飞控硬件、数传模块、GPS、分电板等…

每天40分玩转Django:Django缓存

一、Django缓存概述 在高并发的Web应用中,缓存是提高性能的重要手段。通过缓存频繁访问的数据,可以显著减少数据库查询和渲染模板的时间,从而加快响应速度,提升用户体验。Django提供了多层级的缓存方案,可以灵活地满足不同场景下的缓存需求。 Django支持的缓存方式包括: 视图…

GraphRAG 框架哪家强?选择最适合你智能问答系统的框架

GraphRAG 框架哪家强&#xff1f;选择最适合你智能问答系统的框架 点击进入&#xff1a;GraphRAG系列文章-Nano-GraphRAG&#xff1a;打造轻量级医疗诊断助手 点击进入&#xff1a;GraphRAG系列文章-突破传统知识管理瓶颈&#xff1a;LlamaIndex GraphRAG 让企业知识问答更智能…

Mac电脑python多版本环境安装与切换

我当前是python3.9.6环境&#xff0c;需要使用3.9.8环境&#xff0c;通过brew安装3.9.8版本&#xff0c;然后通过pyenv切换环境 步骤 1: 安装 pyenv brew install pyenv brew install pyenv-virtualenv 步骤 2: 安装 Python 3.9.8&#xff08;使用 pyenv 安装指定版本的 Pyth…

Redis--持久化策略(AOF与RDB)

持久化策略&#xff08;AOF与RDB&#xff09; 持久化Redis如何实现数据不丢失&#xff1f;RDB 快照是如何实现的呢&#xff1f;执行时机RDB原理执行快照时&#xff0c;数据能被修改吗&#xff1f; AOF持久化是怎么实现的&#xff1f;AOF原理三种写回策略AOF重写机制 RDB和AOF合…

C高级:思维导图Day2

目录 总览1 总览2 总览1 压缩与解压缩 打包与解包 软连接与硬链接 ubuntu下关机与重启指令 总览2 结束

pwntools用法

pwntools 是一个Python库&#xff0c; 用于编写二进制漏洞利用&#xff08;exploitation&#xff09;脚本 功能&#xff1a; 远程连接和本地连接&#xff1a; 支持通过TCP/UDP连接远程服务或与本地进程进行交互。Shellcode和ROP链构造&#xff1a; 提供了便捷的工具来生成和利…

【每日学点鸿蒙知识】placement设置top、组件携带自定义参数、主动隐藏输入框、Web设置字体、对话框设置全屏宽

1、popup组件placement设置top没有生效&#xff1f; 可以用offset属性将popup往下边偏移一下 来规避 2、组件携带自定义参数的接口是哪个&#xff1f; 参考链接&#xff1a;https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-universal-attributes-…

PyTorch快速入门教程【小土堆】之优化器

视频地址优化器&#xff08;一&#xff09;_哔哩哔哩_bilibili import torch import torchvision from torch import nn from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential from torch.utils.data import DataLoaderdataset torchvision.datasets.CIFAR1…

数据库篇:mysql内置函数

前言 sql 是程序开发员绕不开的一项技能&#xff0c;而mysql是当前最流行的数据库&#xff0c;熟知其内置的一些函数&#xff0c;可以使我们平时的开发工作更加顺畅和方便 时间日期函数 字符串函数 数学计算相关函数 条件判断函数 加密和压缩函数 聚合函数 格式或类型转…

C# 中 Webclient和Httpclient

在C#中&#xff0c;WebClient和HttpClient&#xff0c;这两个类都是用于发起HTTP请求的客户端&#xff0c;它们在使用API上传文件或数据时有不同的优缺点和应用场景。在C#中WebClient是一种较早的网络客户端&#xff0c;而HttpClient是后期提供的更现代的、功能更强大的HTTP客户…

权限获得第一步

权限获得第一步 下载打开附件 给了一串加密的密文 一般都是用MD5加密&#xff0c;每一段分别解码一下 第一段不行&#xff0c;试一下第二段 这里发现第二段可以解码出来&#xff0c;这应该就是密码了 flag{3617656}

HTML 轮播图(Carousel)详细讲解

HTML 轮播图&#xff08;Carousel&#xff09;详细讲解 轮播图&#xff08;Carousel&#xff09;是一种常见的用户界面组件&#xff0c;用于在同一位置展示多个图像或内容&#xff0c;允许用户通过滑动或自动播放的方式查看不同的内容。它通常用于展示产品、图片、广告等。 1…