.NET C# 读写Excel及转换DataTable

news2024/9/22 13:31:29

目录

  • .NET C# 读写Excel及转换DataTable
    • 1. 依赖库
    • 2. Nuget包与版本
    • 3. ExcelUtil
      • 3.1 Excel sheet 转 DataTable
      • 3.2 Excel sheet 转 DataSet
      • 3.3 DataTable 转 Excel sheet
      • 3.4 DataSet 转 Excel
      • 3.5 私有方法

.NET C# 读写Excel及转换DataTable

1. 依赖库

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

2. Nuget包与版本

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

3. ExcelUtil

3.1 Excel sheet 转 DataTable

/// <summary>
/// Excel sheet 转 DataTable
/// </summary>
/// <param name="excelFilePath">Excel文件路径</param>
/// <param name="sheetName">Sheet名称</param>
/// <returns>结果DataTable</returns>
public static DataTable? FromExcel(string excelFilePath, string sheetName)
{
    DataTable dataTable = new DataTable(sheetName);
    IWorkbook wb = GetWorkbook(excelFilePath);
    if (wb == null)
    {
        return null;
    }
    ISheet ws = wb.GetSheet(sheetName);
    if (ws == null)
    {
        return null;
    }
    if (ws.LastRowNum < 1)
    {
        return dataTable;
    }
    int maxColumnNum = 0;
    int rowNum = ws.LastRowNum + 1;
    for (int rowIdx = 0; rowIdx < rowNum; rowIdx++)
    {
        IRow row = ws.GetRow(0);
        if (row != null && row.LastCellNum > maxColumnNum)
        {
            maxColumnNum = row.LastCellNum;
        }
    }

    IRow headerRow = ws.GetRow(0);

    for (int columnIdx = 0; columnIdx < maxColumnNum; columnIdx++)
    {
        string columnName = string.Empty;
        if (headerRow != null)
        {
            ICell cell = headerRow.GetCell(columnIdx);
            if (cell == null)
            {
                continue;
            }
            columnName = cell.StringCellValue;
        }
        if (string.IsNullOrEmpty(columnName))
        {
            columnName = $"column_{columnIdx + 1}";
        }
        string columnTempName = columnName;
        int tag = 0;
        while (dataTable.Columns.Contains(columnTempName))
        {
            columnTempName = columnName + $"_{++tag}";
        }
        dataTable.Columns.Add(columnTempName);
    }

    if (rowNum <= 1)
    {
        return dataTable;
    }
    for (int rowIdx = 1; rowIdx < rowNum; rowIdx++)
    {
        DataRow dataRow = dataTable.NewRow();
        for (int columnIdx = 0; columnIdx < maxColumnNum; columnIdx++)
        {
            IRow row = ws.GetRow(rowIdx);
            if (row == null)
            {
                continue;
            }
            ICell cell = row.GetCell(columnIdx);
            if (cell == null)
            {
                continue;
            }
            dataRow[columnIdx] = GetCellValue(cell);
        }
        dataTable.Rows.Add(dataRow);
    }
    return dataTable;
}

3.2 Excel sheet 转 DataSet

/// <summary>
/// Excel sheet 转 DataSet
/// </summary>
/// <param name="excelFilePath">Excel文件路径</param>
/// <returns>结果DataSet</returns>
public static DataSet? FromExcel(string excelFilePath)
{
    IWorkbook wb = GetWorkbook(excelFilePath);
    if (wb == null)
    {
        return null;
    }
    DataSet ds = new DataSet();
    for (int i = 0; i < wb.NumberOfSheets; i++)
    {
        ISheet sheet = wb.GetSheetAt(i);
        DataTable? dt = FromExcel(excelFilePath, sheet.SheetName);
        if (dt == null)
        {
            continue;
        }
        ds.Tables.Add(dt);
    }
    return ds;
}

3.3 DataTable 转 Excel sheet

/// <summary>
/// DataTable 转 Excel sheet
/// </summary>
/// <param name="excelFilePath">Excel文件路径</param>
/// <param name="dataTable">DataTable实例</param>
/// <param name="sheetName">Sheet名称</param>
/// <returns>转换结果</returns>
public static bool ToExcel(string excelFilePath, DataTable dataTable, string sheetName = "")
{
    IWorkbook wb = GetWorkbook(excelFilePath);
    if (wb == null)
    {
        return false;
    }
    if (string.IsNullOrEmpty(sheetName))
    {
        if (string.IsNullOrEmpty(dataTable.TableName))
        {
            sheetName = "Sheet";
        }
        else
        {
            sheetName = dataTable.TableName;
        }
    }

    int numberOfSheets = wb.NumberOfSheets;
    if (numberOfSheets > 0)
    {
        List<string> sheetNames = new List<string>();
        for (int sheetIdx = 0; sheetIdx < numberOfSheets; sheetIdx++)
        {
            sheetNames.Add(wb.GetSheetName(sheetIdx).ToLower());
        }
        int tag = 0;
        string sheetTempName = sheetName;
        while (sheetNames.Contains(sheetTempName.ToLower()))
        {
            sheetTempName = $"{sheetName}_{++tag}";
        }
        sheetName = sheetTempName;
    }

    ISheet ws = wb.CreateSheet(sheetName);
    IRow headerRow = ws.CreateRow(0);
    for (int columnIdx = 0; columnIdx < dataTable.Columns.Count; columnIdx++)
    {
        string columnName = dataTable.Columns[columnIdx].ColumnName;
        ICell newCell = headerRow.CreateCell(columnIdx);
        newCell.SetCellValue(columnName);
    }

    for (int rowIdx = 0; rowIdx < dataTable.Rows.Count; rowIdx++)
    {
        IRow row = ws.CreateRow(rowIdx + 1);
        for (int columnIdx = 0; columnIdx < dataTable.Columns.Count; columnIdx++)
        {
            object value = dataTable.Rows[rowIdx][columnIdx];
            string cellStringValue = value?.ToString() ?? string.Empty;
            ICell cell = row.CreateCell(columnIdx);
            cell.SetCellValue(cellStringValue);
        }
    }

    FileStream fs = File.OpenWrite(excelFilePath);
    try
    {
        wb.Write(fs, false);
        return true;
    }
    catch (Exception ex)
    {
        // 异常处理...
        return false;
    }
    finally 
    {
        try { fs?.Close(); } catch { } 
    }
}

3.4 DataSet 转 Excel

/// <summary>
/// DataSet 转 Excel
/// </summary>
/// <param name="excelFilePath">Excel文件路径</param>
/// <param name="dataSet">DataSet实例</param>
/// <returns>转换结果</returns>
public static bool ToExcel(string excelFilePath, DataSet dataSet)
{
    bool allSuccess = true;
    foreach (DataTable dataTable in dataSet.Tables)
    {
        bool success = ToExcel(excelFilePath, dataTable);
        if (!success)
        {
            allSuccess = false;
        }
    }
    return allSuccess;
}

3.5 私有方法

private static IWorkbook GetWorkbook(string excelFilePath)
{
    string extension = Path.GetExtension(excelFilePath);
    IWorkbook wb = null;
    FileStream fs = null;
    try
    {
        if (!File.Exists(excelFilePath))
        {
            if (extension == ".xlsx" || extension == "xlsx")
                wb = new XSSFWorkbook();
            else if (extension == ".xls" || extension == "xls")
                wb = new HSSFWorkbook();
            else
            {
                AppLogger.Instance.Error($"错误文件类型{extension}!");
                return null;
            }
        }
        else
        {
            fs = File.Open(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            if (extension == ".xlsx" || extension == "xlsx")
                wb = new XSSFWorkbook(fs);
            else if (extension == ".xls" || extension == "xls")
                wb = new HSSFWorkbook(fs);
            else
            {
                AppLogger.Instance.Error($"错误文件类型{extension}!");
                return null;
            }
        }
        return wb;
    }
    catch (Exception ex)
    {
        AppLogger.Instance.Error("读取Excel文件失败!", ex);
        return null;
    }
    finally { if (fs != null) try { fs.Close(); } catch { } }
}
static object? GetCellValue(ICell cell)
{
    if (cell == null)
        return null;
    switch (cell.CellType)
    {
        case CellType.Blank: //BLANK:  
            return null;
        case CellType.Boolean: //BOOLEAN:  
            return cell.BooleanCellValue;
        case CellType.Numeric: //NUMERIC:  
            return cell.NumericCellValue;
        case CellType.String: //STRING:  
            return cell.StringCellValue;
        case CellType.Error: //ERROR:  
            return cell.ErrorCellValue;
        case CellType.Formula: //FORMULA:  
        default:
            return "=" + cell.CellFormula;
    }
}

cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return “=” + cell.CellFormula;
}
}




本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1814037.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

[数据集][目标检测]中国象棋检测数据集VOC+YOLO格式300张12类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;300 标注数量(xml文件个数)&#xff1a;300 标注数量(txt文件个数)&#xff1a;300 标注类别…

串口通信的基本概念

串口通信&#xff08;Serial Communications&#xff09;的基本概念可以归纳为以下几个方面&#xff1a; 1、定义与原理&#xff1a; 串口通信是一种通过串行接口进行数据传输的通信方式。它可以将接收来自CPU的并行数据字符转换为连续的串行数据流发送出去&#xff0c;同时可…

大学四年没写过一行代码?真实的计算机专业到底如何?

最近我帮一个学弟做了一个网站当作课程项目&#xff0c;我做好了发给他。他却问我怎么打开&#xff0c;可以用 eclipse 吗&#xff1f;当时直接给我整不会了。这个学弟是通过我们学校的一个代做项目群认识的&#xff0c;这个群有 600 多人&#xff0c;而且天天有人问有没有代做…

C# Web控件与数据感应之模板循环输出

目录 关于模板循环输出 准备数据源 ​范例运行环境 RepeatHtml 方法 设计与实现 如何获取模板内容 getOuterHtml 方法 getInnerHtml 方法 调用示例 小结 关于模板循环输出 数据感应也即数据捆绑&#xff0c;是一种动态的&#xff0c;Web控件与数据源之间的交互&…

国内前十款品质优秀贵金属交易平台app最新排名(功能评测)

投资者如果想要成功进行贵金属投资&#xff0c;则需要掌握相应的技巧和知识。首先&#xff0c;需要对市场进行充分的研究和分析&#xff0c;了解市场走势和资讯&#xff0c;确保自己能够作出明智的投资决策。其次&#xff0c;需要在投资时控制好风险&#xff0c;不将全部资产投…

Angular封装高德地图组件实现输入框搜索,地图点击选地点

Angular封装高德地图组件实现输入框搜索,地图点击选地点(Angular17版本) 话不多说直接上代码 创建一个独立组件 html代码: <div style"position: relative;"><input #searchInput nz-input placeholder"请输入地址"/><div #mapContaine…

ai变声小妙招:分享5个免费变声器,建议收藏!

你曾想过模仿别人的声音吗&#xff1f;也许你看过电影&#xff0c;并为电影中可能出现的变声而惊叹不已。但你知道在现实生活中也可以变声吗&#xff1f;虽然它可能不像你在大屏幕上看到的那样令人印象深刻&#xff0c;但它仍然可以为各种目的带来乐趣和帮助。在以下情况下&…

6月1号关于伊拉克COC清关严控

伊拉克目的港清关严控&#xff0c;所有管控范围内的产品务必申请COC证书&#xff0c; 到港货物&#xff0c;也可以补办了 具体咨询 办理伊拉克COC认证的流程包括&#xff1a; 准备必要的文件&#xff0c;如装箱单、形式发票、产品的测试报告&#xff08;已有测试报告的无需重…

Flutter笔记:关于WebView插件的用法(上)

Flutter笔记 关于WebView插件的用法&#xff08;上&#xff09; - 文章信息 - Author: 李俊才 (jcLee95) Visit me at CSDN: https://jclee95.blog.csdn.netMy WebSite&#xff1a;http://thispage.tech/Email: 291148484163.com. Shenzhen ChinaAddress of this article:htt…

从AI大模型电视,看正在被改写的家庭智能交互

工业时代&#xff0c;内燃机未曾抵达的地方皆被看作“工业之废土”&#xff1b;信息化的今天&#xff0c;未能被AI染指的领域亦或成为“信息之孤岛”。 没有危言耸听。犹记去年&#xff0c;ChatGPT4.0横空出世——凭超强的自然语言处理能力锻造“上帝之手”&#xff0c;所到之…

【介绍下Pandas,什么是Pandas?】

&#x1f308;个人主页: 程序员不想敲代码啊 &#x1f3c6;CSDN优质创作者&#xff0c;CSDN实力新星&#xff0c;CSDN博客专家 &#x1f44d;点赞⭐评论⭐收藏 &#x1f91d;希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出指正&#xff0c;让我们共…

Spire.PDF for .NET【文档操作】演示:将新的 PDF 页面插入到指定索引处的现有 PDF 中

Spire.PDF 完美支持将多页 PDF 拆分为单页。但是&#xff0c;更常见的情况是&#xff0c;您可能希望提取选定的页面范围并保存为新的 PDF 文档。在本文中&#xff0c;您将学习如何通过 Spire.PDF 在 C#、VB.NET 中根据页面范围拆分 PDF 文件。 Spire.PDF for .NET 是一款独立 …

ArcGIS JSAPI 高级教程 - ArcGIS Maps SDK for JavaScript - 探测效果(地图探测、地图窥探)

ArcGIS JSAPI 高级教程 - ArcGIS Maps SDK for JavaScript - 探测效果&#xff08;地图探测、地图窥探&#xff09; 核心代码完整代码&#xff1a;在线示例 ArcGIS Maps SDK for JavaScript 从 4.29 开始增加 RenderNode 类&#xff0c;可以添加数据以及操作 FBO&#xff08;Ma…

助力草莓智能自动化采摘,基于YOLOv5全系列【n/s/m/l/x】参数模型开发构建果园种植采摘场景下草莓成熟度智能检测识别系统

随着科技的飞速发展&#xff0c;人工智能&#xff08;AI&#xff09;技术已经渗透到我们生活的方方面面&#xff0c;从智能家居到自动驾驶&#xff0c;再到医疗健康&#xff0c;其影响力无处不在。然而&#xff0c;当我们把目光转向中国的农业领域时&#xff0c;一个令人惊讶的…

四川古力未来科技抖音小店打造品质生活,可靠之选引领潮流

在当今数字化快速发展的时代&#xff0c;电商平台如雨后春笋般涌现&#xff0c;抖音小店作为其中的佼佼者&#xff0c;凭借其独特的短视频电商模式&#xff0c;迅速吸引了大批年轻消费者的目光。而在众多的抖音小店中&#xff0c;四川古力未来科技抖音小店凭借其卓越的品质和专…

SwiftUI 利用 Swizz 黑魔法为系统创建的默认对象插入新协议方法(六)

功能需求 在 SwiftUI 的开发中,我们往往需要借助底层 UIKit 的“上帝之手”来进一步实现额外的定制功能。比如,在可拖放(Dragable)SwiftUI 的实现中,会缺失拖放取消的回调方法让我们这些秃头码农们“欲哭无泪” 如上图所示,我们在拖放取消时将界面中的一切改变都恢复如初…

机器学习-监督学习6大核心算法技术精讲与代码实战

监督学习线性回归、逻辑回归、决策树、支持向量机、K近邻、朴素贝叶斯算法精讲&#xff0c;模型评估精讲 关注作者&#xff0c;复旦AI博士&#xff0c;分享AI领域与云服务领域全维度开发技术。拥有10年互联网服务架构、AI产品研发经验、团队管理经验&#xff0c;同济本复旦硕博…

载波相移CPS-SPWM调制方法的simulink建模与仿真

目录 1.课题概述 2.系统仿真结果 3.核心程序与模型 4.系统原理简介 5.完整工程文件 1.课题概述 载波相移CPS-SPWM调制方法的simulink建模与仿真&#xff0c;载波相移PWM方法&#xff1a; 2.系统仿真结果 单极倍频 釆用 调制波 反相 法 &#xff0c; 基本调制原理为 &…

【计算机毕业设计】259基于微信小程序的医院综合服务平台

&#x1f64a;作者简介&#xff1a;拥有多年开发工作经验&#xff0c;分享技术代码帮助学生学习&#xff0c;独立完成自己的项目或者毕业设计。 代码可以私聊博主获取。&#x1f339;赠送计算机毕业设计600个选题excel文件&#xff0c;帮助大学选题。赠送开题报告模板&#xff…

西门子学习笔记13 - mtqq库项目

这是我整合过后的mqtt库的下载地址 https://download.csdn.net/download/qq_61916672/89423266https://download.csdn.net/download/qq_61916672/89423266