zoukankan      html  css  js  c++  java
  • 把Excel转换成DataTable,Excel2003+

    在数据处理的时候,我们会Excel(包含2003、2007、2010等)转换成DataTable,以便进一步操作

    1、怎么访问Excel文件呢?我们可以通过OLEDB接口访问,如下:

            private string GetConStr(string ExcelPath)
            {
                string path = ExcelPath;
                if (!File.Exists(path))
                    return null;
    string str2 = Path.GetExtension(path).ToLower(); if ((str2 != ".xls") && (str2 != ".xlsx")) return null;
    string str3 = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source =" + path + "; Extended Properties=Excel 8.0"; if (str2 == ".xlsx") str3 = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source=" + path + "; Extended Properties=Excel 12.0"; return str3; }

    2、读取Excel的数据到DataTable

            public DataTable ExcelToDataTable(string ExcelPath)
            {
                return ExcelToDataTable(ExcelPath, null);
            }
    
            public DataTable ExcelToDataTable(string ExcelPath, string SheetName)
            {
                string conStr = GetConStr(ExcelPath);
                if (string.IsNullOrEmpty(conStr))
                    return null;
    OleDbConnection connection = new OleDbConnection(conStr); connection.Open(); if (string.IsNullOrEmpty(SheetName)) SheetName = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
    else if (!SheetName.Contains("$")) SheetName = SheetName + "$";
    OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [" + SheetName + "]", conStr); DataSet dataSet = new DataSet(); adapter.Fill(dataSet, "[" + SheetName + "$]"); connection.Close(); return dataSet.Tables[0]; }
  • 相关阅读:
    自定义组件 -- android联系人
    ListView嵌套出现的问题
    编译Speex生成so库文件(android-speex)
    MacOs终端忽略大小写
    Eclipse报错:Setting property 'source' to 'org.eclipse.jst.jee.server:test1' did no
    Eclipse 反编译插件安装jad
    spring默认启动位置以及contextConfigLocation设置源码解析
    git使用2
    Git常用命令
    spring MVC配置详解
  • 原文地址:https://www.cnblogs.com/yuejin/p/3457724.html
Copyright © 2011-2022 走看看