/// <summary>
/// 获取Excel内容。
/// </summary>
/// <param name="sheetName">工作表名称,例:sheet1</param>
/// <param name="filePath">Excel路径</param>
/// <returns></returns>
public static DataTable GetTableFromExcel(string sheetName, string filePath, string where = "")
{
string connStrTemplate = string.Empty;
string fileType = System.IO.Path.GetExtension(filePath);
if (string.IsNullOrEmpty(fileType)) return null;
if (filePath == ".xls")
connStrTemplate = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connStrTemplate = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
//connStrTemplate = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\""; //const string connStrTemplate = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;\"";
DataTable dt = null;
if (!System.IO.File.Exists(filePath))
{
// don't find file
return null;
}
OleDbConnection conn = new OleDbConnection(string.Format(connStrTemplate, filePath));
try
{
conn.Open();
if (sheetName == null || sheetName.Trim().Length == )
{
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = schemaTable.Rows[]["TABLE_NAME"].ToString().Trim();
} OleDbDataAdapter da = null;
DataSet ds = new DataSet(); ;
string strSQL = "Select * From [" + sheetName + "$]";
if (!string.IsNullOrWhiteSpace(where))
{
strSQL = string.Format("Select * From [" + sheetName + "] Where {0}", where);
}
try
{
da = new OleDbDataAdapter(strSQL, conn);
da.Fill(ds);
}
catch (Exception er)
{
da = new OleDbDataAdapter("Select * From [sheet1$]", conn);
da.Fill(ds);
}
dt = ds.Tables[];
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
} return dt;
}

//获取名称:

 /// <summary>
/// 获取sheet名
/// </summary>
/// <param name="excelFile">Excel文件名及路径</param>
/// <returns></returns>
public static string[] GetExcelSheetNames(string fileName)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
string connString = string.Empty;
string FileType = fileName.Substring(fileName.LastIndexOf("."));
if (FileType == ".xls")
connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + fileName + ";Extended Properties=Excel 8.0;";
else//.xlsx
connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
// 创建连接对象
objConn = new OleDbConnection(connString);
// 打开数据库连接
objConn.Open();
// 得到包含数据架构的数据表
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = ;
// 添加工作表名称到字符串数组
foreach (DataRow row in dt.Rows)
{
string strSheetTableName = row["TABLE_NAME"].ToString();
//过滤无效SheetName
if (strSheetTableName.Contains("$") && strSheetTableName.Replace("'", "").EndsWith("$"))
{
excelSheets[i] = strSheetTableName.Substring(, strSheetTableName.Length - );
}
i++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
// 清理
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}

C# 连接Excel,获取表格数据,获取多个sheet中的数据,获取多个sheet名的更多相关文章

  1. SQL语句的使用,SELECT - 从数据库表中获取数据 UPDATE - 更新数据库表中的数据 DELETE - 从数据库表中删除数据 INSERT INTO - 向数据库表中插入数据

    SQL DML 和 DDL 可以把 SQL 分为两个部分:数据操作语言 (DML) 和 数据定义语言 (DDL). SQL (结构化查询语言)是用于执行查询的语法. 但是 SQL 语言也包含用于更新. ...

  2. 用于获取或设置Web.config/*.exe.config中节点数据的辅助类

    1. 用于获取或设置Web.config/*.exe.config中节点数据的辅助类 /**//// <summary> /// 用于获取或设置Web.config/*.exe.confi ...

  3. python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图

    python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图 # coding=utf-8 from openpyxl import load_workbook ...

  4. C#-WinForm-ListView-表格式展示数据、如何将数据库中的数据展示到ListView中、如何对选中的项进行修改

    在展示数据库中不知道数量的数据时怎么展示最好呢?--表格 ListView - 表格形式展示数据 ListView 常用属性 HeaderStyle - "详细信息"视图中列标头的 ...

  5. 2000w数据,redis中只存放20w的数据,如何保证redis中的数据都是热点数据

    redis 内存数据集大小上升到一定大小的时候,就会施行数据淘汰策略. redis 提供 6种数据淘汰策略:voltile-lru:从已设置过期时间的数据集(server.db[i].expires) ...

  6. 2000w数据,redis中只存20w的数据,如何保证redis中的数据都是热点数据

    redis 内存数据集大小上升到一定大小的时候,就会施行数据淘汰策略.redis 提供 6种数据淘汰策略: voltile-lru:从已设置过期时间的数据集(server.db[i].expires) ...

  7. js遍历获取表格内数据方法

    1.一般的表格结构如下 <table> <tr> <td>id</td> <td>name</td> </tr> & ...

  8. Android中通过代码获取arrays.xml文件中的数据

    android工程res/valuse文件夹下的arrays.xml文件中用于放各种数组数据,比如字符串数组.整型数组等,数组中的数据可能是具体的值,也有可能是对资源数据的引用,下面针对这两种情况通过 ...

  9. 将Excel表中的数据导入到数据库

    网上查到的有参考价值的就一家,自己调试发现可行.感谢原创文章:将Excel中数据导入数据库(一) using System; using System.Collections.Generic; usi ...

随机推荐

  1. (十二)Bind读取配置到C#实例

    继续上一节的,接下来用Options或者Bind把json文件里的配置转成C#的实体,相互之间映射起来.首先新建一个asp.net core mvc项目OptionsBindSample Startu ...

  2. 用react+redux+webpack搭建项目一些疑惑

    --save-dev开发用 例如:webpack --save开发和发布用 例如:react

  3. linux---postgresql的安装和配置

    postgresql的安装:源码安装(推荐):http://my.oschina.net/hippora/blog/375292 1.tar -xjvf postgresql-9.3.4.tar.bz ...

  4. Oracle Linux下使用sqlplus的edit命令

    1.使当前会话生效 define_editor=vi SQL> select * from dual; D - X SQL> edit Wrote file afiedt.buf 21 1 ...

  5. Linux下tree的使用介绍

    1.在ubuntu系统中默认是没有tree这个命令的,需要安装,用下面的命令就可以安装tree这个命令工具sudo apt-get install tree. 2.首先来说说使用tree这个命令,就是 ...

  6. Python网络编程UDP服务器与客服端简单例子

    [转载] https://blog.csdn.net/hu330459076/article/details/7868028 UDP服务器代码: #!/usr/bin/env python # -*- ...

  7. 【机器学习实验】scikit-learn的主要模块和基本使用

    [机器学习实验]scikit-learn的主要模块和基本使用 引言 对于一些开始搞机器学习算法有害怕下手的小朋友,该如何快速入门,这让人挺挣扎的.在从事数据科学的人中,最常用的工具就是R和Python ...

  8. Foobar 2000增加APE播放支持的方法

    这里说明一下APE,它是一种常用的无损音乐的存储格式,通常会有将原始音乐光盘数字化后存储的APE文件搭配一个CUE文件使用.这个APE存储了音乐的原始数据,而CUE文件则是一个索引文件,用来标记音乐光 ...

  9. Concurrent - 多线程

    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11426916.html Java中有几种方法可以实现一个线程? 继承Thread类(不支持多继承) 实 ...

  10. Java8使用实现Runnable接口方式创建新线程的方法

    环境介绍 JDK版本:1.8 开发架构:spring boot 2.x 日志:slf4j 实现步骤 Runnable接口中只有一个run()方法,它是非Thread类子类的类提供的一种激活方式.一个类 ...