2017-06-02 72 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; 
       } 
相关问题