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.pswp.cn/web/64535.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/64535.shtml
英文地址,請注明出處:http://en.pswp.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…