如何腾讯云二级域名做网站,嘉兴网站建设公司,凡科网站登录入口,郴州网站设计今天是2023年6月26日#xff0c;我有一个excel表要读数据#xff0c;然后放到winform程序来处理#xff0c;网上的资料太旧#xff0c;很多用不起来#xff0c;试了一个可以使用#xff0c;记录一下#xff1a;
一、excel文件后缀需要小写。 二、用VS2022建一个winform…今天是2023年6月26日我有一个excel表要读数据然后放到winform程序来处理网上的资料太旧很多用不起来试了一个可以使用记录一下
一、excel文件后缀需要小写。 二、用VS2022建一个winform程序在NuGet中安装NPOI 三、C#程序代码读取excel数据感觉速度还是可以很快 全部程序代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;namespace readexcel
{public partial class Form1 : Form{public class GT_table{public int id { get; set; }public string t1 { get; set; }public string t2 { get; set; }}public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){DataTable dt ExcelToDatatable(D:\20231025.xlsx, Sheet1, true);//将excel表格数据存入list集合中//EachdayTX定义的类字段值对应excel表中的每一列ListGT_table table new ListGT_table();foreach (DataRow dr in dt.Rows){GT_table line new GT_table{id Convert.ToInt32(dr[0]),t1 dr[1].ToString(),t2 dr[2].ToString(), };listBox1.Items.Add(line.id , line.t1 , line.t2);table.Add(line);}}#region 读取Excel数据/// summary/// 将excel中的数据导入到DataTable中/// /summary/// param namefileName文件路径/param/// param namesheetNameexcel工作薄sheet的名称/param/// param nameisFirstRowColumn第一行是否是DataTable的列名true是/param/// returns返回的DataTable/returnspublic static DataTable ExcelToDatatable(string fileName, string sheetName, bool isFirstRowColumn){ISheet sheet null;DataTable data new DataTable();int startRow 0;FileStream fs;IWorkbook workbook null;int cellCount 0;//列数int rowCount 0;//行数try{fs new FileStream(fileName, FileMode.Open, FileAccess.Read);if (fileName.IndexOf(.xlsx) 0) // 2007版本{workbook new XSSFWorkbook(fs);}else if (fileName.IndexOf(.xls) 0) // 2003版本{workbook new HSSFWorkbook(fs);}if (sheetName ! null){sheet workbook.GetSheet(sheetName);//根据给定的sheet名称获取数据}else{//也可以根据sheet编号来获取数据sheet workbook.GetSheetAt(0);//获取第几个sheet表此处表示如果没有给定sheet名称默认是第一个sheet表 }if (sheet ! null){IRow firstRow sheet.GetRow(0);cellCount firstRow.LastCellNum; //第一行最后一个cell的编号 即总的列数if (isFirstRowColumn)//如果第一行是标题行{for (int i firstRow.FirstCellNum; i cellCount; i)//第一行列数循环{DataColumn column new DataColumn(firstRow.GetCell(i).StringCellValue);//获取标题data.Columns.Add(column);//添加列}startRow sheet.FirstRowNum 1;//1即第二行第一行0从开始}else{startRow sheet.FirstRowNum;//0}//最后一行的标号rowCount sheet.LastRowNum;for (int i startRow; i rowCount; i)//循环遍历所有行{IRow row sheet.GetRow(i);//第几行if (row null){continue; //没有数据的行默认是null;}//将excel表每一行的数据添加到datatable的行中DataRow dataRow data.NewRow();for (int j row.FirstCellNum; j cellCount; j){if (row.GetCell(j) ! null) //同理没有数据的单元格都默认是null{dataRow[j] row.GetCell(j).ToString();}}data.Rows.Add(dataRow);}}return data;}catch (Exception ex){Console.WriteLine(Exception: ex.Message);return null;}}#endregion}
}