C#代码实现把Excel文件转化为DataTable,根据Excel的文件后缀名不同,用不同的方法来进行实现,下面通过根据Excel文件的两种后缀名(*.xlsx和*.xls)分别来实现。获取文件后缀名的方法是:Path.GetExtension(fileName)方法,通过引用:using System.IO;实现代码如下:(其中以下代码中出现的filename都是带盘符的绝对路径)

  • 根据Excel文件的后缀名不同调用的主方法

     private DataTable FileToDataTable(string fileName)
    {
    DataTable dt = new DataTable();
    string extendName = Path.GetExtension(fileName);//获取文件的后缀名
    switch (extendName.ToLower())
    {
    case ".xls":
    dt = XlsToDataTable(fileName);
    break;
    case ".xlsx":
    dt = XlsxToDataTable(fileName);
    break;
    default:
    break;
    }
    return dt;
    }
  • XlsToDataTable()

     private DataTable XlsToDataTable(string fileName)
    {
    DataTable dataTable = new DataTable();
    Stream stream = null;
    try
    {
    stream = File.OpenRead(fileName);
    HSSFWorkbook hssfworkbook = new HSSFWorkbook(stream);
    HSSFSheet hssfsheet = (HSSFSheet)hssfworkbook.GetSheetAt(hssfworkbook.ActiveSheetIndex);
    HSSFRow hssfrow = (HSSFRow)hssfsheet.GetRow();
    int lastCellNum = (int)hssfrow.LastCellNum;
    for (int i = (int)hssfrow.FirstCellNum; i < lastCellNum; i++)
    {
    DataColumn column = new DataColumn(hssfrow.GetCell(i).StringCellValue);
    dataTable.Columns.Add(column);
    }
    dataTable.TableName = hssfsheet.SheetName;
    int lastRowNum = hssfsheet.LastRowNum;
    //列名后,从TABLE第二行开始进行填充数据
    for (int i = hssfsheet.FirstRowNum + ; i < hssfsheet.LastRowNum; i++)//
    {
    HSSFRow hssfrow2 = (HSSFRow)hssfsheet.GetRow(i);
    DataRow dataRow = dataTable.NewRow();
    for (int j = (int)hssfrow2.FirstCellNum; j < lastCellNum; j++)//
    {
    dataRow[j] = hssfrow2.GetCell(j);//
    }
    dataTable.Rows.Add(dataRow);
    }
    stream.Close();
    }
    catch (Exception ex)
    {
    ScriptManager.RegisterStartupScript(Page, GetType(), "alertForm", "alert(' Xls to DataTable: " + ex.Message + "');", true);
    }
    finally
    {
    if (stream != null)
    {
    stream.Close();
    }
    }
    return dataTable;
    }
  • XlsxToDataTable()
    public DataTable XlsxToDataTable(string vFilePath)
    {
    DataTable dataTable = new DataTable();
    try
    {
    SLDocument sldocument = new SLDocument(vFilePath);
    dataTable.TableName = sldocument.GetSheetNames()[];
    SLWorksheetStatistics worksheetStatistics = sldocument.GetWorksheetStatistics();
    int startColumnIndex = worksheetStatistics.StartColumnIndex;
    int endColumnIndex = worksheetStatistics.EndColumnIndex;
    int startRowIndex = worksheetStatistics.StartRowIndex;
    int endRowIndex = worksheetStatistics.EndRowIndex;
    for (int i = startColumnIndex; i <= endColumnIndex; i++)
    {
    SLRstType cellValueAsRstType = sldocument.GetCellValueAsRstType(, i);
    dataTable.Columns.Add(new DataColumn(cellValueAsRstType.GetText(), typeof(string)));
    }
    for (int j = startRowIndex + ; j <= endRowIndex; j++)
    {
    DataRow dataRow = dataTable.NewRow();
    for (int i = startColumnIndex; i <= endColumnIndex; i++)
    {
    dataRow[i - ] = sldocument.GetCellValueAsString(j, i);
    }
    dataTable.Rows.Add(dataRow);
    }
    }
    catch (Exception ex)
    {
    throw new Exception("Xlsx to DataTable: \n" + ex.Message);
    }
    return dataTable;
    }

C#实现EXCEL表格转DataTable的更多相关文章

  1. C#调用NPOI组件读取excel表格数据转为datatable写入word表格中并向word中插入图片/文字/书签 获得书签列表

    调用word的com组件将400条数据导入word表格中耗时10分钟简直不能忍受,使用NPOI组件耗时4秒钟.但是NPOI中替换书签内容的功能不知道是不支持还是没找到. 辅助类 Excel表格数据与D ...

  2. DataTable数据与Excel表格的相互转换

    using Excel = Microsoft.Office.Interop.Excel; private static Excel.Application m_xlApp = null; /// & ...

  3. C#读取Excel表格中数据并返回datatable

    在软件开发的过程中,经常用到从excel表格中读取数据作为数据源,以下整理了一个有效的读取excel表格的方法. DataTable GetDataTable(string tableName,str ...

  4. 将Excel表格数据转换成Datatable

    /// <summary> /// 将Excel表格数据转换成Datatable /// </summary> /// <param name="fileUrl ...

  5. .NET环境下导出Excel表格的两种方式和导入两种类型的Excel表格

    一.导出Excel表格的两种方式,其中两种方式指的是导出XML数据类型的Excel(即保存的时候可以只需要修改扩展名为.xls)和真正的Excel这两种. using System; using Sy ...

  6. asp.net数据导出到excel表格,并设置表格样式

    1.首先在项目中添加引用

  7. 【c#操作office】--OleDbDataAdapter 与OleDbDataReader方式读取excel,并转换为datatable

    OleDbDataAdapter方式: /// <summary> /// 读取excel的表格放到DataTable中 ---OleDbDataAdapter /// </summ ...

  8. 用NPOI、C#操作Excel表格生成班级成绩单

    在C#中利用NPOI操作Excel表格非常方便,几乎上支持所有的Excel表格本身所有的功能,如字体设置.颜色设置.单元格合并.数值计算.页眉页脚等等. 这里准备使用NPOI生成一个班级成绩单Exce ...

  9. C#程序从Excel表格中读取数据并进行处理

    今天做了一个Excel表格数据处理的事情,因为数据量表较大(接近7000条)所以处理起来有点麻烦,于是写了一个程序, 先将程序记下以便将来查找. using System; using System. ...

随机推荐

  1. Activiti7工作流+SpringBoot

    文章目录 一. Activiti相关概念 1. Activiti介绍 2. 核心类 2.1 ProcessEngine 2.2 服务(Service)类 2.2.1 TaskService 2.2.2 ...

  2. LuaForWindows_v5.1.4-45和lua-5.1.4.tar.gz

    Lua学习笔记(一) 安装调试环境 Lua学习笔记(一) 安装调试环境     觉得自己是该掌握一门脚本语言的时候了,虽然曾经用过C# 和JavaScript 写过Unity3D的脚本.但是,总觉得那 ...

  3. CSS中常用的简写模式

    一.font属性简写 font-style:字体样式 normal 默认值.浏览器显示一个标准的字体样式. italic 浏览器会显示一个斜体的字体样式. oblique 浏览器会显示一个倾斜的字体样 ...

  4. 2018-8-10-VisualStudio-自定义外部命令

    title author date CreateTime categories VisualStudio 自定义外部命令 lindexi 2018-08-10 19:16:53 +0800 2018- ...

  5. 2019年第二阶段我要变强个人训练赛第八场 B.序列(seq)

    传送门 B.序列(seq) •题目描述 给出一个长度为n的序列a,每次对序列进行一下的某一个操作. •输入 第一行两个整数n,q表示序列长度和操作个数. 接下来一行n个数,表示序列a. 接下来q行表示 ...

  6. H3C 路由的来源

  7. H3C IPv6邻居发现协议

  8. linux 阻塞 open 作为对 EBUSY 的替代

    当设备不可存取, 返回一个错误常常是最合理的方法, 但是有些情况用户可能更愿意等待 设备. 例如, 如果一个数据通讯通道既用于规律地预期地传送报告(使用 crontab), 也用于根据 用户的需要偶尔 ...

  9. yum安装错误:CRITICAL:yum.cli:Config Error: Error accessing file for config file:///home/linux/+

    上网搜了一下然后自己总结一份 : 出现原因:yum可能没有,或者损坏 解决: 第一步:下载   wget  http://yum.baseurl.org/download/3.2/yum-3.2.28 ...

  10. 数据预处理以及探索性分析(EDA)

    1.根据某个列进行groupby,判断是否存在重复列. # Count the unique variables (if we got different weight values, # for e ...