C#.NET reads and writes Excel table data (teaching by hand)

1. Read the content of the excel table

(1) First in the program: "Reference" right-click - click "Manage NuGet Package" (I have already introduced it here, so it will show that there is NPOI in the reference)

 

(2) Search for "NPOI" in "Browse", select the appropriate version to install (need to be connected to the Internet)

 

(3) Introduce the corresponding namespace in the program, and write the package code to read the excel table (universal)

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) Call the above method of reading the excel table, read the data and access

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; }
        }            

2. Write data into excel table

(1) Also follow the first step in reading excel above, and add NPOI references.

(2) Add a namespace and write the code to write data into the excel table

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) Call the above code written into the excel table to write data

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; }
     }

Guess you like

Origin blog.csdn.net/ucic_0000001/article/details/127538825