c#读取excel内容内容示例分享
程序员文章站
2024-02-23 22:38:52
1、excel 需是.xls 格式2、添加引用microsoft.office.interop.excel.dll
复制代码 代码如下:using system;usin...
1、excel 需是.xls 格式
2、添加引用microsoft.office.interop.excel.dll
复制代码 代码如下:
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.data;
using system.data.oledb;
using excel = microsoft.office.interop.excel;
using system.diagnostics;
namespace readexcel
{
class program
{
static void main(string[] args)
{
string filename = @"d:\transferplant\111.xls";
datatable dt = exceltodataset(filename);
if (dt.rows.count > 0)
{
for (int i = 0; i < dt.rows.count; i++)
{
console.writeline(dt.rows[i][0].tostring());
}
}
}
static public datatable exceltodataset(string filename)
{
string strcon = " provider = microsoft.jet.oledb.4.0 ; data source = "+filename+";extended properties=excel 8.0";
oledbconnection conn = new oledbconnection(strcon);
conn.open();
//返回excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等
datatable dtsheetname = conn.getoledbschematable(oledbschemaguid.tables, new object[] { null, null, null, "table" });
//包含excel中表名的字符串数组
string[] strtablenames = new string[dtsheetname.rows.count];
for (int k = 0; k < dtsheetname.rows.count; k++)
{
strtablenames[k] = dtsheetname.rows[k]["table_name"].tostring();
}
oledbdataadapter mycommand = null;
datatable dt = new datatable();
//从指定的表明查询数据,可先把所有表明列出来供用户选择
string strexcel = "select * from [" + strtablenames[0] + "]";
mycommand = new oledbdataadapter(strexcel, strcon);
mycommand.fill(dt);
return dt;
}
}
}
上一篇: 更改Mysql root用户密码