使用c#从excelfile“* .xlsx”获取数据到数组中

时间:2016-04-06 21:20:58

标签: c#

文件路径是@“E:\ BCFNA-orig-1.xsl” excel文件由9列和500行组成,我希望将每行的数据转换为数组int [] NumberOfInputs = {7,4,4,4,2,4,5,5,0}; “数组中的值应该来自excel文件,在我的程序中使用它,而不是从下一行获取数据。

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);
                }
            }

2 个答案:

答案 0 :(得分:0)

Zahra,没有人在这里回答问题是为了回答他们。我们回答是因为其他人帮助了我们,所以我们想要回馈。您对“使用所有参考组件的完整代码”的态度似乎要求很高。

说完了。 xlsx是一种专有格式。您需要像ExcelLibrary这样的工具才能执行此操作。尽管此答案与写入xlsx更相关,但它仍应为您提供更多选项:https://stackoverflow.com/a/2603625/550975

答案 1 :(得分:0)

我建议使用我的工具Npoi.Mapper,它基于流行的图书馆NPOI。您可以使用基于约定的映射或显式映射直接导入和导出POCO类型。

从Excel(XLS或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");

导出对象

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