您当前的位置: 首页 > 技术文章 > 编程语言

C# .NET读取和写入Excel表数据(手把手教)

作者: 时间:2023-09-19阅读数:人阅读

一、读取excel表内容

(1)首先在程序:“引用”右键--点击“管理NuGet程序包” (我这里是已经引入过了,所以会显示引用中有NPOI)

C# .NET读取和写入Excel表数据(手把手教)(图1)

 

(2)在“浏览”处搜索“NPOI”,选择适当版本安装(需要联网)

C# .NET读取和写入Excel表数据(手把手教)(图2)

 

(3)在程序中引入相应的命名空间,编写读取excel表格的封装代码(万能)

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;


#region 读取Excel数据
        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名,true是</param>
        /// <returns>返回的DataTable</returns>
        public 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

(4)调用上述读取excel表的方法,读取数据并存取

DataTable dt = ExcelToDatatable(@"C:\Users\Administrator\Desktop\35t敞顶箱(2)\4-11月连续日期每天需求量.xlsx", "Sheet1", true);
//将excel表格数据存入list集合中
//EachdayTX定义的类,字段值对应excel表中的每一列
List<EachdayTX> eachdayTX = new List<EachdayTX>();
foreach (DataRow dr in dt.Rows)
            {
                EachdayTX model = new EachdayTX
                {
                    Sta=dr[0].ToString()+"站",//excel表中第一列的值,依次类推
                    Date=dr[1].ToString(),
                    TXnum=Convert.ToInt32(dr[2])
                };
                eachdayTX.Add(model);
            }
public class EachdayTX
        {
            public string Sta { get; set; }
            public string Date { get; set; }
            public int TXnum { get; set; }
        }            

二、数据写入excel表

(1)同样按照上面读取excel中的第一步,添加NPOI引用。

(2)添加命名空间,编写将数据写入excel表的代码

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;


//此处是将list集合写入excel表,Supply也是自己定义的类,每一个字段对应需要写入excel表的每一列的数据
//一次最多能写65535行数据,超过需将list集合拆分,分多次写入
 #region 写入excel
        public static bool ListToExcel(List<Supply> list)
        {
            bool result = false;
            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("Sheet1");//创建一个名称为Sheet0的表;
            IRow row = sheet.CreateRow(0);//(第一行写标题)
            row.CreateCell(0).SetCellValue("标题1");//第一列标题,以此类推
            row.CreateCell(1).SetCellValue("标题2");
            row.CreateCell(2).SetCellValue("标题3");
            int count = list.Count;//
            int max = 65535;//最大行数限制
            if (count < max)
            {
//每一行依次写入
                for (int i = 0; i < list.Count; i++)
                {
                    row = sheet.CreateRow(i + 1);//i+1:从第二行开始写入(第一行可同理写标题),i从第一行写入
                    row.CreateCell(0).SetCellValue(list[i].Value1);//第一列的值
                    row.CreateCell(1).SetCellValue(list[i].Value2);//第二列的值
                    row.CreateCell(2).SetCellValue(list[i].Value3);
                }
//文件写入的位置
                using (FileStream fs = File.OpenWrite(@"C:\Users\20882\Desktop\结果.xls"))
                {
                    workbook.Write(fs);//向打开的这个xls文件中写入数据  
                    result = true;
                }
            }
            else
            {
                Console.WriteLine("超过行数限制!");
                result = false;
            }

            return result;

        }
        #endregion

(3)调用上述写入excel表的代码,写入数据

List<Supply> data = new List<Supply>();
//假设data 已经存入了数据,根据自己需要添加数据
data.Add(new Supply
         {
             Value1 = "1",
             Value2= "haha",
             Value3="111",
         });



bool a = ListToExcel(data);//调用写入excel的方法,写入数据



public class Supply
     {
         public string Value1{ get; set; }
         public string Value2{ get; set; }
         public string Value3{ get; set; }
     }

本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:licqi@yunshuaiweb.com

标签: excel c# .net
加载中~
如果您对我们的成果表示认同并且觉得对你有所帮助可以给我们捐赠。您的帮助是对我们最大的支持和动力!
捐赠我们
扫码支持 扫码支持
扫码捐赠,你说多少就多少
2
5
10
20
50
自定义
您当前余额:元
支付宝
微信
余额

打开支付宝扫一扫,即可进行扫码捐赠哦

打开微信扫一扫,即可进行扫码捐赠哦

打开QQ钱包扫一扫,即可进行扫码捐赠哦