在C#中有很多种读取excel表格的方式有oldb、epplus、npoi、文件流,今天在使用net5框架不能使用oldb方式读取,于是使用了npoi,本文介绍一下npoi读取方式,其他方式读取请移步另一篇文章https://blog.csdn.net/qq_39569480/article/details/105573807

在包管理器安装npoi

这里在安装2.6时报了个错,可参考我零一篇文章http://t.csdn.cn/YuXHW
https://blog.csdn.net/qq_39569480/article/details/130653685?spm=1001.2014.3001.5501

话不多说上代码,读取表格

调用

using 引用
using NPOI.HSSF.UserModel;//导出xls格式用HSSF
using NPOI.XSSF.UserModel;//导出xlsx格式用XSSF
using NPOI.SS.UserModel;

string path = @"G:\新建文件夹\上传数据.xls";var (Result, Msg, Dt) = ExcelToTable(path);
     /// <summary>/// Excel导入成DataTble/// </summary>/// <param name="file">导入路径(包含文件名与扩展名)</param>/// <returns></returns>public static (bool,string, DataTable) ExcelToTable(string file){try{DataTable dt = new DataTable();IWorkbook workbook;string fileExt = Path.GetExtension(file).ToLower();using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)){if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }if (workbook == null) { return (false,"没有读取到数据",null); }ISheet sheet = workbook.GetSheetAt(0);//表头  IRow header = sheet.GetRow(sheet.FirstRowNum);List<int> columns = new List<int>();for (int i = 0; i < header.LastCellNum; i++){object obj = GetValueType(header.GetCell(i));if (obj == null || obj.ToString() == string.Empty){dt.Columns.Add(new DataColumn("Columns" + i.ToString()));}elsedt.Columns.Add(new DataColumn(obj.ToString()));columns.Add(i);}//数据  for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++){DataRow dr = dt.NewRow();bool hasValue = false;foreach (int j in columns){dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));if (dr[j] != null && dr[j].ToString() != string.Empty){hasValue = true;}}if (hasValue){dt.Rows.Add(dr);}}}return (true,"", dt);}catch (Exception e){return (false,e.Message,null);}}/// <summary>/// 获取单元格类型/// </summary>/// <param name="cell">目标单元格</param>/// <returns></returns>private static object GetValueType(ICell cell){if (cell == null)return null;switch (cell.CellType){case CellType.Blank:return null;case CellType.Boolean:return cell.BooleanCellValue;case CellType.Numeric:return cell.NumericCellValue;case CellType.String:return cell.StringCellValue;case CellType.Error:return cell.ErrorCellValue;case CellType.Formula:default:return "=" + cell.CellFormula;}}

写入表格 xls、xlsx

调用

         //这里先调用上边读取excel文件的方法  把数据读到datatable中   然后修改了两个列的值再写回到excel文件中string path = @"G:\新建文件夹\上传数据.xls";var (Result, Msg, Dt) = ExcelToTable(path);if (Result){for (int i = 0; i < Dt.Rows.Count; i++){Dt.Rows[i]["上传结果"] = "成功";Dt.Rows[i]["上传信息"] = "12312312";}bool asads= DataTableToExcel(Dt, path);MessageBox.Show(asads.ToString());}else{MessageBox.Show(Result.ToString()+ Msg);}
/// <summary>/// 将datatable写入到excel(xls)/// </summary>/// <param name="dt">datatable</param>/// <param name="filepath">写入的文件路径</param>/// <returns></returns>public static bool DataTableToExcel(DataTable dt, string filepath){bool result = false;IWorkbook workbook = null;FileStream fs = null;IRow row = null;ISheet sheet = null;ICell cell = null;try{if (dt != null && dt.Rows.Count > 0){workbook = new HSSFWorkbook();sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表  int rowCount = dt.Rows.Count;//行数  int columnCount = dt.Columns.Count;//列数  string cellnum;//设置列头  row = sheet.CreateRow(0);//excel第一行设为列头  for (int c = 0; c < columnCount; c++){cell = row.CreateCell(c);cell.SetCellValue(dt.Columns[c].ColumnName);}//设置每行每列的单元格,  for (int i = 0; i < rowCount; i++){row = sheet.CreateRow(i + 1);for (int j = 0; j < columnCount; j++){cell = row.CreateCell(j);//excel第二行开始写入数据//cell.SetCellValue(dt.Rows[i][j].ToString());//保存单元格格式为数字if (j < 2){cell.SetCellValue(dt.Rows[i][j].ToString());}else{ SetCellValue(cell, dt.Rows[i][j]);//if (dt.Rows[i][j] is DBNull)//{//    cell.SetCellValue(dt.Rows[i][j].ToString());//}//else//{//   cellnum = Convert.ToString(dt.Rows[i][j].ToString());//    cell.SetCellValue(cellnum);//}}}}if (System.IO.File.Exists(filepath)){if (MessageBox.Show("该文件已存在!确定覆盖吗?", "WARNING", MessageBoxButtons.OKCancel) == DialogResult.OK){File.Delete(filepath);}else{return false;}}using (fs = File.OpenWrite(filepath)){workbook.Write(fs,true);//向打开的这个xls文件中写入数据result = true;}}return result;}catch (Exception ex){MessageBox.Show(ex.Message);if (fs != null){fs.Close();}return false;}}/// <summary>/// Datable导出成Excel(xlsx)/// </summary>/// <param name="dt"></param>/// <param name="file">导出路径(包括文件名与扩展名)</param>public static (bool,string) TableToExcel(DataTable dt, string file){try{IWorkbook workbook;string fileExt = Path.GetExtension(file).ToLower();workbook = new XSSFWorkbook();导出xls格式用HSSF     导出xlsx格式用XSSFISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("sheet0") : workbook.CreateSheet(dt.TableName);//表头  IRow row = sheet.CreateRow(0);for (int i = 0; i < dt.Columns.Count; i++){ICell cell = row.CreateCell(i);cell.SetCellValue(dt.Columns[i].ColumnName);}//数据  for (int i = 0; i < dt.Rows.Count; i++){IRow row1 = sheet.CreateRow(i + 1);for (int j = 0; j < dt.Columns.Count; j++){ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString());}}//保存为Excel文件 using (MemoryStream ms = new MemoryStream()){workbook.Write(ms, true);//ms.Close();//ms.Dispose();} using (FileStream fs = new FileStream(file, FileMode.Create/*, FileAccess.Write*/)){workbook.Write(fs, true);//fs.Close();//workbook = null; }  return (true,"");}catch (Exception e){return (false,e.Message);}}/// <summary>/// 获取数据类型并设置单元格数据类型写入到单元格/// </summary>/// <param name="cell">目标单元格</param>/// <param name="obj">数据值</param>/// <returns></returns>public static void SetCellValue(ICell cell, object obj){if (obj.GetType() == typeof(int)){cell.SetCellValue((int)obj);}else if (obj.GetType() == typeof(double)){cell.SetCellValue((double)obj);}else if (obj.GetType() == typeof(IRichTextString)){cell.SetCellValue((IRichTextString)obj);}else if (obj.GetType() == typeof(string)){cell.SetCellValue(obj.ToString());}else if (obj.GetType() == typeof(DateTime)){cell.SetCellValue((DateTime)obj);}else if (obj.GetType() == typeof(bool)){cell.SetCellValue((bool)obj);}else{cell.SetCellValue(obj.ToString());}}

C# NPOI读写xls、xlsx表格相关推荐

  1. 【数据读写】csv文件与xls/xlsx文件

    目录 一.csv格式与xls/xlsx格式的区别 二.两种文件格式的读写操作 1.csv文件的读/写函数 csvread csvwrite 2.xls/xlsx文件的读/写函数 xlsread xls ...

  2. 用Python一步读写csv、xlsx表格

    需求 代码 测试 需求 python的内置库csv提供了读写csv表格的方法,第三方库openpyxl 提供了读写xlsx表格的方法. 不过,为了避免每次调用这些库时都要回忆其用法,笔者将基本的读写操 ...

  3. NPOI读取xls和xlsx格式

    public static List<KeyValuePair<string, string>> ReadExcelHead() { OpenFileDialog openFi ...

  4. NPOI读写Excel

    1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 ...

  5. python处理excel表格数据-零基础使用Python读写处理Excel表格的方法

    引 由于需要解决大批量Excel处理的事情,与其手工操作还不如写个简单的代码来处理,大致选了一下感觉还是Python最容易操作. 安装库Python环境 首先当然是配环境,不过选Python的一个重要 ...

  6. RobotFramework操作xlsx表格

    RobotFramework操作xlsx表格 tips:直接运行RIDE快捷方式一般看不出报错原因,可以打开cmd命令,然后输入ride.py就可以看到报错原因 目前很多项目用得是xlsx表格,目前封 ...

  7. python的openpyxl模块下载_python解析.xls/.xlsx文件–openpyxl模块(第三方)

    围观人数: 7 标签:book   set   tle   命令行   文件中   不能   charm   读取   pen 第一part:Excel文件的介绍 Microsoft Excel是Mi ...

  8. 在浏览器上打开、预览Excel xlsx表格文件

    现在的HTML5,有了FileReader文件读写API, 真是让javascript的能力大幅提升. 解析zip压缩文件.解析Excel xlsx 表格文档各种文件预览,实现起来也有了可能性,以前的 ...

  9. Java导出大批量数据(文件格式篇xls,xlsx,csv)

    根据最近写出的导出方法 打算在文章中记录总结下学习心得 java导出我准备分为三篇文章介绍 分批查询导出篇https://blog.csdn.net/weixin_56567361/article/d ...

  10. Python将txt数据转换为xls(表格)文件,方便后面做数据分析

    Python我们做数据分析的时候有时候获得数据是txt文件,这时候我们该怎么办呢?下面我给大家教一下这时候应该怎么做? 1.读取txt数据查看:我们就可以看到使用逗号隔开的数据. "&quo ...

最新文章

  1. 吴恩达深度学习笔记3-Course1-Week3【浅层神经网络】
  2. 长春理工计算机学院保研外校,长春理工大学计算机科学技术学院(专业学位)软件工程保研...
  3. USACO4.12Beef McNuggets(背包+数论)
  4. Linux进程命令PS用法笔记
  5. Matlab控制精度
  6. php mysql 查询时间_PHP-MySQL查询需要大量时间才能执行
  7. 【分享】Android JNI实例​
  8. Screaming Frog SEO Spider for Mac进行网页抓取和数据提取的技巧
  9. 2015阿里天池大数据竞赛-Solution
  10. windows 清除记录ftp账号
  11. 全国公共DNS服务器IP地址汇总
  12. 2020最新注册卡密微信在线充值购卡功能(适用于各种网络验证开发)【易语言源码】
  13. [毒]QQ空间出现的伪装QQ登录窗口诈骗
  14. 优矿量化如何完成Alpha对冲模型测试?
  15. ctfshow七夕杯 writeup
  16. 【信号与系统学习笔记 3】—— 系统,以及系统的性质以及判断方法解析
  17. 【软件测试】什么软件测试,软件测试和研发的区别
  18. 三大战略分析方法——SWOT、PEST、波特五力模型
  19. 全国计算机一级考试网上题,全国计算机一级考试精选习题及答案
  20. 高通QCM2290平台组合键进9008

热门文章

  1. 类和对象(上)续——类对象模型和this指针
  2. 流量威胁检测工具开发之路(6)
  3. springmvc三大核心组件
  4. SQL的弱点(1):复杂SQL不易理解,以及软件工程如何来帮忙
  5. 制作可以从SD卡加载文件系统的流程
  6. 2020-3-11python语法知识(5)字符串和字典
  7. Spotfire调试经验——分组累计值的动态计算(Dynamic calculation of grouped accumulated value in Spotfire)
  8. 小技巧!Python生成excel文件的三种方式!
  9. Pycharm专业版直白简易安装流程
  10. Linux网络编程之TCP协议(一版)