c#.net工具类一excel读取与写入(代码片段)

黑喵警员 黑喵警员     2022-12-01     572

关键词:

Excel读取与写入需要依赖第三方类库,这里选择使用比较多、同时不依赖安装Office组件的NPOI。

支持xls和xlsx格式,区分方法详见代码。

在Nuget上找到并安装到项目中:

 

 

 

 

1.Excel读取数据:

  1   public partial class ExcelFile
  2     
  3         /// <summary>
  4         /// 读取Excel文件
  5         /// </summary>
  6         /// <param name="filePath">被读取文件的路径</param>
  7         /// <param name="hasTitle">文件是否包含列头</param>
  8         /// <returns></returns>
  9         public static DataSet Read(string filePath,bool hasTitle = false)
 10         
 11             IWorkbook wk = null;
 12             string extension = Path.GetExtension(filePath);
 13             try
 14             
 15                 FileStream fs = File.OpenRead(filePath);
 16                 if (extension.Equals(".xls"))
 17                 
 18                     //把xls文件中的数据写入wk中
 19                     wk = new HSSFWorkbook(fs);
 20                 
 21                 else
 22                 
 23                     //把xlsx文件中的数据写入wk中
 24                     wk = new XSSFWorkbook(fs);
 25                 
 26 
 27                 fs.Close();
 28 
 29                 DataSet ds = new DataSet();
 30                 for (int tableindex = 0; tableindex < wk.NumberOfSheets; tableindex++)
 31                 
 32                     //读取当前表数据
 33                     ISheet sheet = wk.GetSheetAt(tableindex);
 34 
 35                     IRow row = sheet.GetRow(0);  //读取当前行数据
 36                                                  //LastRowNum 是当前表的总行数-1(注意)
 37 
 38                     DataTable dt = new DataTable();
 39                     dt.TableName = sheet.SheetName;
 40 
 41                     for (int i = 0; i <= sheet.LastRowNum; i++)
 42                     
 43                         row = sheet.GetRow(i);  //读取当前行数据
 44                         if (row != null)
 45                         
 46                             if (hasTitle && i ==0)
 47                             
 48                                 //LastCellNum 是当前行的总列数
 49                                 for (int j = 0; j < row.LastCellNum; j++)
 50                                 
 51                                     //读取该行的第j列数据
 52                                     string value = row.GetCell(j).ToString();
 53                                     DataColumn dataColumn = new DataColumn();
 54                                     dataColumn.ColumnName = value;
 55                                     dataColumn.DataType = typeof(string);
 56                                     dt.Columns.Add(dataColumn);
 57                                 
 58                                 continue;
 59                             
 60 
 61                             
 62                             if (dt.Columns.Count == 0 || dt.Columns.Count != row.LastCellNum)
 63                             
 64                                 for (int j = 0; j < row.LastCellNum; j++)
 65                                 
 66                                     DataColumn dataColumn = new DataColumn();
 67                                     dataColumn.ColumnName = "Column" + j;
 68                                     dataColumn.DataType = typeof(string);
 69                                     dt.Columns.Add(dataColumn);
 70                                 
 71                             
 72 
 73                             DataRow dataRow = dt.NewRow();
 74 
 75                             //LastCellNum 是当前行的总列数
 76                             for (int j = 0; j < row.LastCellNum; j++)
 77                             
 78                                 //读取该行的第j列数据
 79                                 string value = row.GetCell(j).ToString();
 80                                 dataRow[j] = value;
 81                             
 82 
 83                             dt.Rows.Add(dataRow);
 84                         
 85                     
 86                     ds.Tables.Add(dt);
 87                 
 88 
 89                 if (ds.Tables.Count == 0)
 90                 
 91                     return null;
 92                 
 93                 else
 94                 
 95                     return ds;
 96                 
 97             
 98             catch (Exception e)
 99             
100                 throw e;
101             
102         
103     

 

2.Excel写入数据

  1 public partial class ExcelFile
  2     
  3         /// <summary>
  4         /// 读取Excel文件
  5         /// </summary>
  6         /// <param name="filePath">被读取文件的路径</param>
  7         /// <returns></returns>
  8         public static bool Write(DataTable dt,string filePath)
  9         
 10             try
 11             
 12                 //创建一个工作薄  
 13                 IWorkbook workbook = new HSSFWorkbook();
 14 
 15                 //获取文件后缀
 16                 string extension = Path.GetExtension(filePath);
 17 
 18                 //根据指定的文件格式创建对应的类
 19                 if (extension.Equals(".xls"))
 20                 
 21                     workbook = new HSSFWorkbook();
 22                 
 23                 else
 24                 
 25                     workbook = new XSSFWorkbook();
 26                 
 27 
 28                 //创建一个 sheet 表
 29                 ISheet sheet = workbook.CreateSheet();
 30 
 31                 //创建一行
 32                 IRow rowH = sheet.CreateRow(0);
 33 
 34                 //创建一个单元格
 35                 ICell cell = null;
 36 
 37                 //创建单元格样式
 38                 ICellStyle cellStyle = workbook.CreateCellStyle();
 39 
 40                 //创建格式
 41                 IDataFormat dataFormat = workbook.CreateDataFormat();
 42 
 43                 //设置为文本格式,也可以为text,即dataFormat.GetFormat("text")
 44                 cellStyle.DataFormat = dataFormat.GetFormat("0");
 45 
 46                 //设置列名
 47                 foreach (DataColumn col in dt.Columns)
 48                 
 49                     //创建单元格并设置单元格内容
 50                     rowH.CreateCell(col.Ordinal).SetCellValue(col.Caption);
 51 
 52                     //设置单元格格式
 53                     rowH.Cells[col.Ordinal].CellStyle = cellStyle;
 54                 
 55 
 56                 //写入数据
 57                 for (int i = 0; i < dt.Rows.Count; i++)
 58                 
 59                     //跳过第一行,第一行为列名
 60                     IRow row = sheet.CreateRow(i + 1);
 61                     for (int j = 0; j < dt.Columns.Count; j++)
 62                     
 63                         cell = row.CreateCell(j);
 64                         cell.SetCellValue(dt.Rows[i][j].ToString());
 65                         cell.CellStyle = cell.CellStyle;
 66                     
 67                 
 68 
 69                 //设置新建文件路径及名称
 70                 if (File.Exists(filePath))
 71                 
 72                     File.Delete(filePath);
 73                 
 74 
 75                 //创建文件
 76                 //FileStream file = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
 77 
 78                 FileStream fs = File.OpenWrite(filePath);
 79                 workbook.Write(fs);//向打开的这个Excel文件中写入表单并保存。  
 80                 fs.Close();
 81 
 82                 return true;
 83             
 84             catch (Exception ex)
 85             
 86                 throw ex;
 87             
 88 
 89 
 90             #region 老方法
 91 
 92             ////创建工作薄  
 93             //IWorkbook wb = new HSSFWorkbook();
 94             //string extension = Path.GetExtension(filePath);
 95             ////根据指定的文件格式创建对应的类
 96             //if (extension.Equals(".xls"))
 97             //
 98             //    wb = new HSSFWorkbook();
 99             //
100             //else
101             //
102             //    wb = new XSSFWorkbook();
103             //
104 
105             //ICellStyle style1 = wb.CreateCellStyle();//样式
106             //style1.Alignment = HorizontalAlignment.Left;//文字水平对齐方式
107             //style1.VerticalAlignment = VerticalAlignment.Center;//文字垂直对齐方式
108             //                                                    //设置边框
109             //style1.BorderBottom = BorderStyle.Thin;
110             //style1.BorderLeft = BorderStyle.Thin;
111             //style1.BorderRight = BorderStyle.Thin;
112             //style1.BorderTop = BorderStyle.Thin;
113             //style1.WrapText = true;//自动换行
114 
115             //ICellStyle style2 = wb.CreateCellStyle();//样式
116             //IFont font1 = wb.CreateFont();//字体
117             //font1.FontName = "楷体";
118             //font1.Color = HSSFColor.Red.Index;//字体颜色
119             //font1.Boldweight = (short)FontBoldWeight.Normal;//字体加粗样式
120             //style2.SetFont(font1);//样式里的字体设置具体的字体样式
121             //                      //设置背景色
122             //style2.FillForegroundColor = HSSFColor.Yellow.Index;
123             //style2.FillPattern = FillPattern.SolidForeground;
124             //style2.FillBackgroundColor = HSSFColor.Yellow.Index;
125             //style2.Alignment = HorizontalAlignment.Left;//文字水平对齐方式
126             //style2.VerticalAlignment = VerticalAlignment.Center;//文字垂直对齐方式
127 
128             //ICellStyle dateStyle = wb.CreateCellStyle();//样式
129             //dateStyle.Alignment = HorizontalAlignment.Left;//文字水平对齐方式
130             //dateStyle.VerticalAlignment = VerticalAlignment.Center;//文字垂直对齐方式
131             //                                                       //设置数据显示格式
132             //IDataFormat dataFormatCustom = wb.CreateDataFormat();
133             //dateStyle.DataFormat = dataFormatCustom.GetFormat("yyyy-MM-dd HH:mm:ss");
134 
135             ////创建一个表单
136             //ISheet sheet = wb.CreateSheet("Sheet0");
137             ////设置列宽
138             //int[] columnWidth =  10, 10, 20, 10 ;
139             //for (int i = 0; i < columnWidth.Length; i++)
140             //
141             //    //设置列宽度,256*字符数,因为单位是1/256个字符
142             //    sheet.SetColumnWidth(i, 256 * columnWidth[i]);
143             //
144 
145             ////测试数据
146             //int rowCount = 3, columnCount = 4;
147             //object[,] data = 
148             //    "列0", "列1", "列2", "列3",
149             //    "", 400, 5.2, 6.01,
150             //    "", true, "2014-07-02", DateTime.Now
151             //    //日期可以直接传字符串,NPOI会自动识别
152             //    //如果是DateTime类型,则要设置CellStyle.DataFormat,否则会显示为数字
153             //;
154 
155             //IRow row;
156             //ICell cell;
157 
158             //for (int i = 0; i < rowCount; i++)
159             //
160             //    row = sheet.CreateRow(i);//创建第i行
161             //    for (int j = 0; j < columnCount; j++)
162             //    
163             //        cell = row.CreateCell(j);//创建第j列
164             //        cell.CellStyle = j % 2 == 0 ? style1 : style2;
165             //        //根据数据类型设置不同类型的cell
166             //        object obj = data[i, j];
167             //        SetCellValue(cell, data[i, j]);
168             //        //如果是日期,则设置日期显示的格式
169             //        if (obj.GetType() == typeof(DateTime))
170             //        
171             //            cell.CellStyle = dateStyle;
172             //        
173             //        //如果要根据内容自动调整列宽,需要先setCellValue再调用
174             //        //sheet.AutoSizeColumn(j);
175             //    
176             //
177 
178             ////合并单元格,如果要合并的单元格中都有数据,只会保留左上角的
179             ////CellRangeAddress(0, 2, 0, 0),合并0-2行,0-0列的单元格
180             //CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0);
181             //sheet.AddMergedRegion(region);
182 
183             //try
184             //
185             //    FileStream fs = File.OpenWrite(filePath);
186             //    wb.Write(fs);//向打开的这个Excel文件中写入表单并保存。  
187             //    fs.Close();
188             //
189             //catch (Exception e)
190             //
191             //    Debug.WriteLine(e.Message);
192             //
193 
194             #endregion
195         
196     

 

1.javapoi读取写入excel(包括样式)的工具类utils(代码片段)

在工作中经常会遇到操作excel的需求,对于格式简单、统一的excel可以选择EasyExcel来实现功能,很简单方便;而对于复杂的excel文件,如有各式各样的合并单元格、表头不固定、行列跟随业务数据动态变化……格式... 查看详情

unity3d中excel表的读取与写入(代码片段)

 废话不多说,对Excel表的操作少不了要引入第三方库,首先我们需要引入 Excel.dll和 ICSharpCode.SharpZipLib.dll,这两个类库在网上都能找到;然后我们还需要引入 System.Data.dll,这个类库在Unity3D的安装路径下的 Editor... 查看详情

csvfileutil读取写入csv文件简单工具类(代码片段)

参考github大神源码总结一下最简单的工具类记录一下/***@descriptionCSV文件读取和输出工具类.<br/>*@authormichael*@date2019/05/16*@versionCopyright(c)2019,[email protected]AllRightsReserved.*/publicclassCSVFileUtilprivatesta 查看详情

c零基础视频-48-文件的写入与读取(代码片段)

目录fread与fwritefread与fwrite从信息的转换角度看,文件的读取与写入,其实就是信息在文件介质(磁盘)与内存之间进行转换。文件读取(fread),就是将磁盘中的文件内容,读取进内存中;而文件写入(fwrite),就是将内存中的... 查看详情

day7_读取数据库,写入到excel里面(代码片段)

importpymysql,xlwtdefcon_mysql(sql):conn=pymysql.connect(host=‘211.149.218.16‘,user=‘jxz‘,password=‘123456‘,db=‘jxz‘,charset=‘utf8‘)cur=conn.cursor()cur.execute(sql)res=cur.fetchall()cur.close()conn.c 查看详情

easyexcel专题excel读取写入上传和下载(代码片段)

一、将10万条数据从Excel读取出来        读取支持多标题,我们只需要指定最后一行的标题的行号即可,例如上述excel标题的行号为1,因此需要设置headRowNumber为1。          定义User类,使用User类映射excel... 查看详情

easyexcel专题excel读取写入上传和下载(代码片段)

一、将10万条数据从Excel读取出来        读取支持多标题,我们只需要指定最后一行的标题的行号即可,例如上述excel标题的行号为1,因此需要设置headRowNumber为1。          定义User类,使用User类映射excel... 查看详情

easyexcel专题excel读取写入上传和下载(代码片段)

一、将10万条数据从Excel读取出来        读取支持多标题,我们只需要指定最后一行的标题的行号即可,例如上述excel标题的行号为1,因此需要设置headRowNumber为1。          定义User类,使用User类映射excel... 查看详情

分散读取与聚集写入(代码片段)

分散读取与聚集写入分散读取(scatteringReads):将通道中的数据分散到多个缓冲区中聚集写入(gatheringWrites):将多个缓冲区的数据聚集到通道中packagecom.toov5.Nio;importjava.io.IOException;importjava.io.RandomAccessFile;importjava.nio.ByteBuffer;importjava.n 查看详情

pandas读取和写入excel多个sheet表单(代码片段)

一、读取单个表单importpandasaspdexcel_reader=pd.ExcelFile(‘文件.xlsx‘)#指定文件sheet_names=excel_reader.sheet_names#读取文件的所有表单名,得到列表df_data=excel_reader.parse(sheet_name=sheet_names[i])#读取表单的内容,i是表单名的索引,等价于pd.read_e 查看详情

文件内容的写入与读取(代码片段)

1//文件的读取方式一2//直接读取文件34stringtextContent=File.ReadAllText("路径","读取的文件内容类型");56//文件读取方式二78stringFileName="";//表示路径9using(FlieStreamfs=newFlieStream(‘FlieName‘,FileMode.open,FileAccess.Read))1011using(S 查看详情

unity文件写入与读取(代码片段)

usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEditor;usingUnityEngine.SceneManagement;usingSystem;usingSystem.IO;usingSystem.Runtime.InteropServices;publicclassGri 查看详情

excel文件的读取和写入(代码片段)

...建excel文件test.xls和写入内容  2、excel文件的内容读取importxlrdwork=xlrd.open_workbook(‘test.xls‘,‘r‘)sheet=work.sheet_by_index(0)print(sheet.nrows)#查看行数print(sheet.cell_value(1,2))#获取单元格内容3、向excel写入内容importxlrdfromxlutils.copyimpor... 查看详情

在.net7使用npoi读取excel如此简单(代码片段)

本文主要介绍了.net7简单使用NPOI读取Excel表格。NPOI是指构建在POI3.x版本之上的一个程序,NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作。NPOI这个老牌控件不错,只需要很少的代码就可以实现,下面是一步一步实... 查看详情

01-使用easyexcel读取和写入excel文件(代码片段)

一、EasyExcel介绍Java解析、生成Excel比较有名的框架有Apachepoi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel... 查看详情

python求excel每列平均值并追加写入到最后一行读取修改表格(代码片段)

 #-*-encoding:utf-8-*-#读取excel表格importxlrdfromxlutils.copyimportcopy##第一步,读取#excel表格在哪里filename="./students.xls"workbook=xlrd.open_workbook(filename)sheetnames=workbook.shee 查看详情

python3关于excel文件格式xls之读取写入和追加(代码片段)

Python 操作xls格式的表格文件依赖模块:1、xlwt2、xlrd3、xlutilsPython封装xls功能代码片段importxlwtimportcsvimportxlrdfromxlutils.copyimportcopydefwrite_excel_xls_head(path,sheet_name,value):'''定义excelhead头部信 查看详情

自动化神器!python批量读取身份证信息写入excel(代码片段)

今天分享一个实用技能,利用Python批量读取身份证信息写入Excel。读取以图片形式的身份证为例,信息读取我们使用百度文字识别OCR来实现,百度接口提供了免费额度,日常使用基本差不多够了,下面来具体看... 查看详情