zoukankan      html  css  js  c++  java
  • C#读取Excel文档

    上面分别是Excel文档的内容和读取结果;

    奉上C#源代码:

    using System;
    using System.Data;
    using System.Data.OleDb;
    
    namespace ReadExcel
    {
        class ReadExcel
        {
            static void Main()
            {
                DataSet dataset = ReadExcel.ExcelToDS(@"D:	est1.xls");
                DataTable table = dataset.Tables["table1"];
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    DataRow row = table.Rows[i];
                    /* 默认会把Excel的第一行作为列名,当HDR=NO时则以序号取数,或者以F1,F2,F3……的方式取数
                     * 当HDR=NO时则以序号取数,或者以F1,F2,F3……的方式取数
                     * 例如:row[0],row[1],row[2]或者row[F1],row[F2],row[F3]
                     */
                    string country = Convert.ToString(row["国家"]);
                    string nationality = Convert.ToString(row["民族"]);
                    Console.WriteLine(country + "	" + nationality);
                }
                Console.ReadKey();
            }
            public static DataSet ExcelToDS(string Path)
            {
                string filename = System.IO.Path.GetFileName(Path);//文件名
                string extension = System.IO.Path.GetExtension(Path);//扩展名 “.xlsx”
                string strConn = string.Empty;
                if (extension == "xls")
                {
                    //默认以Excel文档的第一行作为列名,如果不需要则设置:HDR=NO
                    //strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties='Excel 8.0;HDR=NO'";
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
                }
                else
                {
                    //strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
                    strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";Extended Properties='Excel 12.0; IMEX=1'";
                }
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                string strExcel = "";
                OleDbDataAdapter myCommand = null;
                DataSet ds = null;
                strExcel = "select * from [sheet1$]";
                myCommand = new OleDbDataAdapter(strExcel, strConn);
                ds = new DataSet();
                myCommand.Fill(ds, "table1");
                return ds;
            }
        }
    }
  • 相关阅读:
    Zookeeper初见
    常见一致性协议(二)
    常见一致性协议(一)
    分布式理论基础
    expose a port on a living Docker container
    tomcat远程调试参数备忘
    bash: ifconfig: command not found
    解决 :java -version出现错误:“could not open `C:Program FilesJavajre7libamd64jvm.cfg”
    centos7 安装 NVIDIA Docker
    解决: httpclient ssl 验证导致死锁问题
  • 原文地址:https://www.cnblogs.com/yangyong-yy/p/5421224.html
Copyright © 2011-2022 走看看