Session

C# 导入Exel文件

电脑版发表于:2021/4/21 9:38

前言


链接Exel方法与链接sqlserver类似(微软自带的链接Exel)


首先引入命名空间

//引入链接Exel的命名空间
using System.Data.OleDb;

引入Exel


配置链接字符串

            //Exel地址
            string url = Server.MapPath("~/Exel/students.xls");
            //Exel链接字符串
            string oledstr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\";Data Source=" + url;

读取数据(与sqlserver类似)

using (OleDbConnection conn = new OleDbConnection(oledstr))
            {
                conn.Open();
                                               //数据表格式[表名$]
                using (OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", conn))
                {
                    OleDbDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        string id = reader[0].ToString();
                        string name = reader[1].ToString();
                        string age = reader[2].ToString();
                        Response.Write("学号是" + id + "  姓名:" + name + "  年龄:" + age + "<br/>");
                    }
                }
            }


关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢