当前位置: 代码网 > it编程>编程语言>Asp.net > C# 读取Execl文件3种方法

C# 读取Execl文件3种方法

2024年08月01日 Asp.net 我要评论
ADO.NET的数据访问对象有Connection,Command、DataReader和DataAdaper等,由于每种.NET Data Provider都有自己的数据访问对象,因此他们的使用方式相似。这里主要介绍OLEDB.NET Data Provider的各种数据访问对象的使用。

方法 

1,使用oledb可以对excel文件进行读取

1.1c#提供的数据连接有哪些

        对于不同的.net数据提供者,ado.net采用不同的connection对象连接数据库。这些connection对我们屏蔽了具体的实现细节,并提供了一种统一的实现方法。

connection类有四种:sqlconnection,oledbconnection,odbcconnection和oracleconnection。

sqlconnetcion类的对象连接是sql server数据库;

oracleconnection类的对象连接oracle数据库;

oledbconneetion连接支持ole db的数据库,如access;

而odbcconnection类的对象连接支持odbc的数据库。

与数据库的所有通讯都是通过connection对象来完成的。

1.2介绍使用oledbonnection来链接各种数据源

        ado.net的数据访问对象有connection,command、datareader和dataadaper等,由于每种.net data provider都有自己的数据访问对象,因此他们的使用方式相似。这里主要介绍oledb.net data provider的各种数据访问对象的使用。

oledbconnection对象

在数据访问中首先必须建立到数据库的物理连接。oledb.net data provider 使用oledbconnection类的对象标识与一个数据库的物理连接。

oledbconnection类的常用属性
属性说明
connectionstring 获取或设置用于打开数据库的字符串
connectiontimeout获取在尝试建立连接时终止尝试并生成错误之前所等待的时间
database获取当前数据库或连接打开后要使用的数据库名称
datasource获取数据源的服务器名或文件名
provider获取在连接字符串的“provider = ” 子句中指定的oledb提供程序的名称
state获取连接的当前状态
oledbconnection类的常用方法
方法说明
open使用connectionstring所指定的属性设置打开数据库连接
close 关闭与数据库的连接,这是关闭任何打开连接的首选方法
createcommand创建并返回一个与oledbconnection关联的oledbcommand对象
changedatabase为打开的oledbconnection更改当前数据库

 1.3建立连接字符串connectionstring

1、直接建立连接字符串

直接建立连接字符串的方式是先创建一个oledbconnection对象,将其connectionstring属性设置为如下:

provider = microsoft.jet.oledb.4.0;data sourse = access数据库;userid = 用户名;password = 密码;

  其中provider和datasource是必选项,如果access数据库没有密码,userid和password可以省略。由于access数据库是基于文件的数据库,因此在实际项目中应该将data source的属性值转换为服务器的绝对路径。最后用open方法打开连接。

1.4代码

        public dataset readexceltodataset(string path)
        {
            //连接字符串
            /* 备注:
            	添加 imex=1 表示将所有列当做字符串读取,实际应该不是这样,
            	系统默认会查看前8行如果有字符串,则该列会识别为字符串列。
            	如果前8行都是数字,则还是会识别为数字列,日期也一样;
            	如果你觉得8行不够或者太多了,则只能修改注册表hkey_local_machine/software/microsoft/jet/4.0/engines/excel/typeguessrows,
            	如果此值为0,则会根据所有行来判断使用什么类型,通常不建议这麽做,除非你的数据量确实比较少
            */
            string connstring = "provider=microsoft.ace.oledb.12.0;data source=" + path + ";extended properties='excel 8.0;imex=1';";

            using (oledbconnection conn = new oledbconnection(connstring))
            {
                conn.open();
                system.data.datatable sheetsname = conn.getoledbschematable(oledbschemaguid.tables, new object[] { null, null, null, "table" });//存放所有的sheet
                dataset set = new dataset();
                for (int i = 0; i < sheetsname.rows.count; i++)
                {
                    string sheetname = sheetsname.rows[i][2].tostring();
                    string sql = string.format("select * from [{0}]", sheetname);
                    oledbdataadapter ada = new oledbdataadapter(sql, connstring);

                    ada.fill(set);
                    set.tables[i].tablename = sheetname;
                }

                return set;

            }
        }

2 ,使用office自带的库

2.1安装库

2.2代码

        //2 ,使用office自带的库
        public system.data.dataset getexceldata(string excelfilepath)
        {
            microsoft.office.interop.excel.application app = new microsoft.office.interop.excel.application();
            microsoft.office.interop.excel.sheets sheets;
            microsoft.office.interop.excel.workbook workbook = null;
            object omissiong = system.reflection.missing.value;

            dataset dataset = new dataset();
            string cellcontent;
            try
            {
                if (app == null)
                {
                    return null;
                }
                workbook = app.workbooks.open(excelfilepath, omissiong, omissiong, omissiong, omissiong, omissiong,
                    omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong);

                sheets = workbook.worksheets;
                for (int p = 1; p <= sheets.count; p++)
                {
                    system.data.datatable dt = new system.data.datatable();
                    microsoft.office.interop.excel.worksheet worksheet = (microsoft.office.interop.excel.worksheet)sheets.get_item(p);//读取第一张表

                    for (int j = 1; j <= worksheet.usedrange.columns.count; j++)
                    {

                        range _range = (microsoft.office.interop.excel.range)worksheet.cells[1, j];
                        if (_range.text.tostring().trim() == "")
                            dt.columns.add("equipment");
                        else
                            dt.columns.add(_range.text.tostring().trim());

                    }
                    for (int i = 2; i <= worksheet.usedrange.rows.count; i++)
                    {
                        datarow dr = dt.newrow();
                        for (int j = 1; j <= worksheet.usedrange.columns.count; j++)
                        {
                            range _range = (microsoft.office.interop.excel.range)worksheet.cells[i, j];
                            cellcontent = (_range.value2 == null) ? "" : _range.text.tostring().trim();
                            dr[j - 1] = cellcontent;
                        }
                        dt.rows.add(dr);
                    }
                    dataset.tables.add(dt);
                }
            }
            finally
            {
                workbook.close(false, omissiong, omissiong);
                system.runtime.interopservices.marshal.releasecomobject(workbook);
                workbook = null;
                app.workbooks.close();
                app.quit();
                system.runtime.interopservices.marshal.releasecomobject(app);
                app = null;
                gc.collect();
                gc.waitforpendingfinalizers();
            }
            return dataset;
        }

3,利用exceldatareader 读取excel文件

3.1安装库

 3.2代码

        //3,利用exceldatareader 读取excel文件
        public dataset readexceltodataset1(string filenmaepath)
        {
            filestream stream = null;
            iexceldatareader excelreader = null;
            dataset dataset = null;
            try
            {
                //stream = file.open(filenmaepath, filemode.open, fileaccess.read);
                stream = new filestream(filenmaepath, filemode.open, fileaccess.read, fileshare.readwrite);
            }
            catch
            {
                return null;
            }
            string extension = path.getextension(filenmaepath);

            if (extension.toupper() == ".xls")
            {
                excelreader = excelreaderfactory.createbinaryreader(stream);
            }
            else if (extension.toupper() == ".xlsx")
            {
                excelreader = excelreaderfactory.createopenxmlreader(stream);
            }
            else
            {
                messagebox.show("格式错误");
                return null;

            }
            //dataset = excelreader.asdataset();//第一行当作数据读取
            dataset = excelreader.asdataset(new exceldatasetconfiguration()
            {
                configuredatatable = (_) => new exceldatatableconfiguration()
                {
                    useheaderrow = true
                }
            });//第一行当作列名读取
            excelreader.close();
            return dataset;
        }

结果

参考文献

c#读取excel表数据_c# 读取excel文件内容-csdn博客

https://www.cnblogs.com/vaevvaev/p/6873367.html

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com