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

一、读取excel表内容

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

 

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

 

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

  • 32
    点赞
  • 170
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
可以使用 Microsoft.Office.Interop.Excel 库来实现将 DataGrid 中的数据写入Excel 中对应的头行列中。 首先需要引用 Microsoft.Office.Interop.Excel 库,然后可以按照以下步骤进行操作: 1. 创建 Excel 应用程序对象和工作簿对象 ``` Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Add(); ``` 2. 获取工作簿中的第一个工作对象 ``` Excel.Worksheet worksheet = workbook.Worksheets[1]; ``` 3. 将 DataGrid 中的写入Excel 的第一行中 ``` for (int i = 0; i < dataGrid.Columns.Count; i++) { worksheet.Cells[1, i + 1] = dataGrid.Columns[i].Header.ToString(); } ``` 4. 将 DataGrid 中的数据写入Excel 中对应的行列中 ``` for (int i = 0; i < dataGrid.Items.Count; i++) { for (int j = 0; j < dataGrid.Columns.Count; j++) { string value = (dataGrid.Items[i] as DataRowView)[j].ToString(); worksheet.Cells[i + 2, j + 1] = value; } } ``` 5. 保存 Excel 文件并关闭应用程序对象 ``` workbook.SaveAs("output.xlsx"); excelApp.Quit(); ``` 完整代码示例: ``` using System.Data; using Excel = Microsoft.Office.Interop.Excel; private void ExportToExcel(DataGrid dataGrid) { Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Add(); Excel.Worksheet worksheet = workbook.Worksheets[1]; // 写入头 for (int i = 0; i < dataGrid.Columns.Count; i++) { worksheet.Cells[1, i + 1] = dataGrid.Columns[i].Header.ToString(); } // 写入数据 for (int i = 0; i < dataGrid.Items.Count; i++) { for (int j = 0; j < dataGrid.Columns.Count; j++) { string value = (dataGrid.Items[i] as DataRowView)[j].ToString(); worksheet.Cells[i + 2, j + 1] = value; } } // 保存并关闭 Excel 应用程序 workbook.SaveAs("output.xlsx"); excelApp.Quit(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值