csharp 阅读Excel

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 阅读Excel相关的知识,希望对你有一定的参考价值。

    public  DataTable exceldata(string filePath)
        {
            DataTable dtexcel = new DataTable();
            bool hasHeaders = false;
            string HDR = hasHeaders ? "Yes" : "No";
            string strConn;

            if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
            else
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

            //Looping a first Sheet of Xl File
            DataRow schemaRow = schemaTable.Rows[0];
            string sheet = schemaRow["TABLE_NAME"].ToString();
                string query = "SELECT  * FROM [" + sheet + "]";
            if (!sheet.EndsWith("_"))
            {

                using (var connection = new OleDbConnection(strConn))
                {
                    using (var command = CreateCommand(query, connection, CommandType.Text))
                    {
                        using (var adapter = CreateAdapter(command))
                        {
                            adapter.Fill(dtexcel);
                        }
                    }
                }

                //OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
                //dtexcel.Locale = CultureInfo.CurrentCulture;
                //daexcel.Fill(dtexcel);
             
            }

            conn.Close();
            return dtexcel;

        }

        OleDbDataAdapter CreateAdapter(OleDbCommand command)
        {
            // ** Factory pattern in action

            var adapter = new OleDbDataAdapter();
            adapter.SelectCommand = command;
            return adapter;
        }
        OleDbCommand CreateCommand(string sql, OleDbConnection conn, CommandType type)
        {
            // ** Factory pattern in action

            var command = new OleDbCommand();
            command.CommandType = type;
            command.Connection = conn;
            command.CommandText = sql;
            
            return command;
        }

以上是关于csharp 阅读Excel的主要内容,如果未能解决你的问题,请参考以下文章

csharp 阅读Excel

csharp 阅读Excel文件

csharp 例如-CSHARP-GroupDocs.AssemblyExamples-GenerateReport-GenerateBulletedListFromJsoninOpenExcel.c

csharp leer excel

csharp .Net Excel导出

csharp leer excel