2017-06-02 32 views
-2

我想從Excel電子表格中獲取單元格的值。該值存儲在sheet1,單元格A2中,該列位於名爲Item的列標題下。下面的代碼總是將該值作爲空值返回。請幫我拿到存儲在A2中的值。如何從存儲在內存中的Excel表中讀取值c#

using Excel; 
using System; 
using System.Collections.Generic; 
using System.Data; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Test 
{ 
    public class ExcelUtil 
    { 
     public static DataTable ExcelToDataTable(string fileName) 
     { 
      FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read); 
      IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx 
         excelReader.IsFirstRowAsColumnNames = true; 
       DataSet result = excelReader.AsDataSet(); 
       DataTableCollection table = result.Tables; 
       DataTable resultTable = table["Sheet1"]; 

       return resultTable; 
     } 

     public static List<Datacollection> dataCol = new List<Datacollection>(); 

     public static void PopulateInCollection(string fileName) 
     { 
      DataTable table = ExcelToDataTable(fileName); 
      //Iterate through all the rows and columns of the Table 
      for (int row = 1; row <= table.Rows.Count; row++) 
      { 
       for (int col = 0; col < table.Columns.Count; col++) 
       { 
        Datacollection dtTable = new Datacollection() 
        { 
         rowNumber = row, 
         colName = table.Columns[col].ColumnName, 
         colValue = table.Rows[row - 1][col].ToString() 
         }; 
         //Add all the details for each row 
         dataCol.Add(dtTable); 
        } 
       } 
      } 

     public static string ReadData(int rowNumber, string columnName) 
     { 
      try 
      { 
       //Retrieving Data using LINQ 
       string data = (from colData in dataCol 
              where colData.colName == columnName && colData.rowNumber == rowNumber 
              select colData.colValue).SingleOrDefault(); 

       //var data = dataCol.Where(x => x.colName == columnName && x.rowNumber == rowNumber).SingleOrDefault().colValue; 
          return data.ToString(); 
      } 
      catch (Exception e) 
      { 
       e.Message.ToString(); 
       return null; 
      } 
     } 

     private static void mytest() 
     { 
      string itemNo = ExcelUtil.ReadData(1, "Item"); 
     } 
    } 

public class Datacollection 
{ 
    public int rowNumber { get; set; } 
    public string colName { get; set; } 
    public string colValue { get; set; } 
} 
} 
+1

哪種方法返回null?你有沒有嘗試調試代碼,看看它爲什麼返回null?我應該如何在我的機器上運行此代碼?我應該打電話給哪種方法? –

+0

@ChetanRanpariya您需要在PC上本地保存一個excel工作表,並有幾行,第一行將有標題,您可以將任何東西放入第二行。是的,我嘗試過調試,但我得到了同樣的錯誤。 :resultTable \t錯誤CS0103:名稱'resultTable'在當前上下文中不存在。 – Tester

+0

我忘了補充說我也有我的初始化類的文件名:ExcelUtil.PopulateInCollection(@「Data.xlsx」);應用程序無法獲取itemno字段的字符串(這是Excel電子表格中的A2) – Tester

回答

-1

嗨,我該代碼將幫助您在

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Data.OleDb; 
using System.Data; 
namespace EXEL_DB 
{ 
public partial class Form1 : Form 
{ 
    OleDbConnection coon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=""C:\A.xls""; Extended properties=""Excel 8.0;HDR=Yes;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0"""); 

    OleDbCommand com; 
    DataTable dt = new DataTable(); 
    OleDbDataAdapter da; 
    public Form1() 
    { 

     coon.Open(); 
     fillgrilll(""); 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     DataView dv = new System.Data.DataView(dt); 

     dv.RowFilter = "group by [langue com] order by [langue com]"; 
     dataGridView1.DataSource = dv; 
    } 

    void fillgrilll(string re) 
    { 
     try 
     { 
      dt.Clear(); 
       // My sheet i name it A but you have to write [A$] 
      da = new OleDbDataAdapter("select * from [A$] where datepart(month,[Shipment Date]) = datepart(month,'06/04/2016')", coon); 
      da.Fill(dt); 
      //dataGridView1.DataSource = dt; 
     } 
     catch { 
      MessageBox.Show("Errr"); 
     } 
    } 
} 
} 

`

0

我找到答案了不少!我需要以下兩行添加到我上面的代碼:

  private static void mytest() 
      { 
       ExcelUtil util = new ExcelUtil(); 
       ExcelUtil.PopulateInCollection(@"c:\datalocation\Data.xlsx"); 

       string itemNo = ExcelUtil.ReadData(1, "Item"); 
      } 

,我不得不修改以下還有:

    public static string ReadData(int rowNumber, string columnName) 
      { 
       try 
       { 
        ////Retrieving Data using LINQ 
        var data = (from colData in dataCol 
           where colData.colName == columnName && colData.rowNumber == rowNumber 
           select colData.colValue).First().ToString(); 

        //var data = dataCol.Where(x => x.colName == columnName && x.rowNumber == rowNumber).SingleOrDefault().colValue; 
        return data; 
       } 
       catch (Exception e) 
       { 
        e.Message.ToString(); 
        return null; 
       } 
相關問題