C# 读取Excel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Data.OleDb;
namespace Collector.Helper
{
public static class ExcelHelper
{
public static System.Collections.Generic.List<string> GetTables(string filepath)
{
List<string> r=new List<string>();
if (File.Exists(filepath))
{
//string connStr="Provider=Microsoft.Jet." + "OLEDB.4.0;Extended Properties=\"Excel 8.0\";Data Source=" + filepath;
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;data source=" + filepath + ";Extended Properties='Excel 12.0 Xml;HDR=YES'";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
for (int i = 0; i < dt.Rows.Count; i++)
{
r.Add(dt.Rows[i][2].ToString().Trim());
}
}
}
return r;
}
public static DataTable GetTableData(string filepath,string tableName)
{
DataTable r = new DataTable();
if (File.Exists(filepath))
{
//string connStr = "Provider=Microsoft.Jet." + "OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=FALSE;IMEX=1\";Data Source=" + filepath;
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;data source=" + filepath + ";Extended Properties='Excel 12.0 Xml;HDR=YES'";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
string sql = "select * from [" + tableName+ "]";
OleDbCommand oc = new OleDbCommand(sql, conn);
OleDbDataAdapter oda = new OleDbDataAdapter(oc);
oda.Fill(r);
}
}
return r;
}
public static System.Collections.Generic.List<string> GetTableFields(string filepath, string tableName)
{
List<string> r=new List<string>();
if (File.Exists(filepath))
{
//string connStr = "Provider=Microsoft.Jet." + "OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=FALSE;IMEX=1\";Data Source=" + filepath;
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;data source=" + filepath + ";Extended Properties='Excel 12.0 Xml;HDR=YES'";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
string sql = "select * from [" + tableName + "] where 1=2";
OleDbCommand oc = new OleDbCommand(sql, conn);
OleDbDataAdapter oda = new OleDbDataAdapter(oc);
DataTable dt = new DataTable();
oda.Fill(dt);
for (int i = 0; i < dt.Columns.Count; i++)
{
r.Add(dt.Columns[i].Caption);
}
}
}
return r;
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 《HelloGitHub》第 106 期
· 数据库服务器 SQL Server 版本升级公告
· 深入理解Mybatis分库分表执行原理
· 使用 Dify + LLM 构建精确任务处理应用