简体   繁体   中英

to get data from excelfile “*.xlsx” into an array using c#

file path is @"E:\\BCFNA-orig-1.xsl" excel file consists of 9 columns and 500 rows i want to get data from each row into an array int[] NumberOfInputs = {7,4,4,4,2,4,5,5,0}; " the values inside array are supposed to get from excel file , use it in my program and than get data from next row.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.IO;

namespace ConsoleApplication3
{
class Program
{
    static void Main()
    {
    }  


public class SomethingSometingExcelClass
{
    public void DoSomethingWithExcel(string filePath)
    {

        List<DataTable> worksheets = ImportExcel(filePath);
        foreach(var item in worksheets){
            foreach (DataRow row in item.Rows)
            {
                //add to array

            }            
        }
     }
    /// <summary>
    /// Imports Data from Microsoft Excel File.
    /// </summary>
    /// <param name="FileName">Filename from which data need to import data    
    /// <returns>List of DataTables, based on the number of sheets</returns>
    private List<DataTable> ImportExcel(string FileName)
    {
        List<DataTable> _dataTables = new List<DataTable>();
        string _ConnectionString = string.Empty;
        string _Extension = Path.GetExtension(FileName);
        //Checking for the extentions, if XLS connect using Jet OleDB                          

        _ConnectionString =
                "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=E:\\BCFNA- 

            orig-1.xls;Extended    

       Properties=Excel 8.0";

        DataTable dataTable = null;

        using (OleDbConnection oleDbConnection =
            new OleDbConnection(string.Format(_ConnectionString, FileName)))
        {
            oleDbConnection.Open();
            //Getting the meta data information.
            //This DataTable will return the details of Sheets in the Excel 

             File.DataTable dbSchema =  
     oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables_Info,  null);
            foreach (DataRow item in dbSchema.Rows)
            {
                //reading data from excel to Data Table
                using (OleDbCommand oleDbCommand = new OleDbCommand())
                {
                    oleDbCommand.Connection = oleDbConnection;
              oleDbCommand.CommandText = string.Format("SELECT * FROM   

              [B1415:J2113]", item["TABLE_NAME"].ToString());
                    using (OleDbDataAdapter oleDbDataAdapter = new 
                    OleDbDataAdapter())
                    {
                        oleDbDataAdapter.SelectCommand = oleDbCommand;
                        dataTable = new 
               DataTable(item["TABLE_NAME"].ToString());
                        oleDbDataAdapter.Fill(dataTable);
                        _dataTables.Add(dataTable);
                    }
                }
            }
        }
        return _dataTables;
    }
       }
         }
          }

     //////////////////////////////////////
           above is the code which i am using to get data from excel but                       

      ///////////////////////////////////////////////////////


      below is the nested loop in which i want to use data
      /////////////////////////////////////////////////
        for (ChromosomeID = 0; ChromosomeID < PopulationSize; ChromosomeID++)
                {
                    Fitness = 0;
                    Altemp = (int[])AlPopulation[ChromosomeID];
                    for (int z = 0; z < 500; z++)
                    {
                        int[] NumberOfInputs = new int[9]; 
            //// this is the array where in which data need to be added

               InputBinary.AddRange(DecBin.Conversion2(NumberOfInputs));

                        for (i = 0; i < Altemp.Length; i++)
                        {
                            AlGenotype[i] = (int)Altemp[i];
                        }
                        Class1 ClsMn = new Class1();
                        AlActiveGenes = ClsMn.ListofActiveNodes(AlGenotype);

                        ClsNetworkProcess ClsNWProcess = new 
                     ClsNetworkProcess();
                        AlOutputs = ClsNWProcess.NetWorkProcess(InputBinary, 

                      AlGenotype, AlActiveGenes);
                        int value = 0;
                        for (i = 0; i < AlOutputs.Count; ++i)
                        {
                            value ^= (int)AlOutputs[i];        // xor the 
                       output of the system
                        }

                        temp = Desired_Output[0];
                        if (value == temp) // compare system Output with  
                    DesiredOutput bit by bit
                            Fitness++;
                        else
                            Fitness = Fitness;
                    }
                    AlFitness.Add(Fitness);
                }
            }

Zahra, no one on here that is answering questions is paid to answer them. We answer because others have helped us so we want to give back. Your attitude of "want a complete code with all reference assemblies used" seems rather demanding.

Having said that. xlsx is a proprietary format. You will need a tool like ExcelLibrary to be able to do this. Even though this answer is more related to writing to xlsx it should still give you some more options: https://stackoverflow.com/a/2603625/550975

I would suggest to use my tool Npoi.Mapper , which is based on popular library NPOI. You can import and export with POCO types directly with convention based mapping, or explicit mapping.

Get objects from Excel (XLS or XLSX)

var mapper = new Mapper("Book1.xlsx");
var objs1 = mapper.Take<SampleClass>("sheet2");

// You can take objects from the same sheet with different type.
var objs2 = mapper.Take<AnotherClass>("sheet2");

Export objects

//var objects = ...
var mapper = new Mapper();
mapper.Save("test.xlsx",  objects, "newSheet", overwrite: false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM