2017-09-28 10 views
0

Excel(.xls)ファイルを読み込むアプリケーションを作成する。 ファイルを読み取ることはできますが、データの数だけが表示されています。 ただし、ファイルからデータを取得できません。リストにファイルデータを保存する方法

Microsoft.Office.Interop.Excel.Application xlApp = new Excel.Application(); 
       Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Landingfolder\file.xls"); 
       Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; 
       Excel.Range xlRange = xlWorksheet.UsedRange; 
       int rowCount = xlRange.Rows.Count; 
       int colCount = xlRange.Columns.Count; 

       for (int i = 1; i <= rowCount; i++) 
       { 
        for (int j = 1; j <= colCount; j++) 
        { 
         //new line 
         if (j == 1) 
          Console.Write("\r\n"); 

         //write the value to the console 
         if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) 
          Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t"); 
         Console.ReadLine(); 


        } 
       } 

正しいプロセスを教えてください。

+0

、表示または他の気にいらないためにどのような方法を意味し、私は、リスト内のすべてのデータを保存する、予想される結果のサンプル –

+0

を提供してください。たとえば、Excelシートには4つの列があります。 id、empName、salary、empDepartment – Bheesham

答えて

1

使用このコードコードの

using System.Data.OleDb; 
using System.IO; 
using System.Data; 

public class Employee 
    { 
     public string Name { get; set; } 

     public string Designation { get; set; } 

     public int? Experience { get; set; } 
    } 


/// <summary> 
     /// Open Connection 
     /// </summary> 
     /// <param name="path"></param> 
     /// <returns></returns> 
     private OleDbConnection OpenConnection(string path) 
     { 
      OleDbConnectio n oledbConn = null; 
      try 
      { 
       if (Path.GetExtension(path) == ".xls") 
        oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + 

"; Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=2\""); 
       else if (Path.GetExtension(path) == ".xlsx") 
        oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + 

path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"); 

       oledbConn.Open(); 
      } 
      catch (Exception ex) 
      { 
       //Error 
      } 
      return oledbConn; 
     } 


/// <summary> 
     /// Extract 'Service Information' sheet 
     /// </summary> 
     /// <param name="oledbConn"></param> 
     private IList<Employee> ExtractEmployeeExcel(OleDbConnection oledbConn) 
     { 
      OleDbCommand cmd = new OleDbCommand(); ; 
      OleDbDataAdapter oleda = new OleDbDataAdapter(); 
      DataSet dsEmployeeInfo = new DataSet(); 

      cmd.Connection = oledbConn; 
      cmd.CommandT ype = CommandType.Text; 
      cmd.CommandT ext = "SELECT * FROM [Employee$]"; //Excel Sheet Name (Employee) 
      oleda = new OleDbDataAdapter(cmd); 
      oleda.Fill (dsEmployeeInfo, "Employee"); 

      var dsEm ployeeInfoList = dsEmployeeInfo.Tables[0].AsEnumerable().Select (s => new Employee 
      { 
       Name = Convert.ToString(s["Name"] ! = DBNull.Value ? s["Name"] : ""), 
       Designation = Convert.ToString(s["Designation"] ! = DBNull.Value ? s["Designation"] : ""), 
       Experience = Convert.ToInt32(s["Experience"]) 
      }).ToList(); 

      return dsEmployeeInfoList; 
     } 

/// <summary> 
     /// Read excel sheet with the user path 
     /// </summary> 
     /// <param name="path"></param> 
     public IList<Employee> ReadExcel(string path) 
     { 
      IList<Employ ee> objEmployeeInfo = new List<Employee>(); 
      try 
      {    
       OleDbConnection oledbConn = OpenConnection(path); 
       if (oledbConn.State == ConnectionState.Open) 
       { 
        objEmployeeInfo = ExtractEmployeeExcel (oledbConn); 
        oledbConn.Close(); 
       } 
      } 
      catch (Exception ex) 
      { 
       // Error 
      } 
      return objEmployeeInfo; 
     } 

使用:ここで

Excelのコンテンツを取得するReadExcel()メソッドを呼び出します。あなたはExcelデータで何をしたいか

string path = @"D:\Employee.xls"; 
     IList<Employee> objExcelCon = ReadExcel(path); 
+0

@Bheeshamあなたが満足している場合は、受け入れるように回答を受け入れる –

+0

私は受け入れました。私はまた、行をループするためにあなたの助けが必要です。 – Bheesham

+0

どのように私はあなたを助けることができます。 –

関連する問題