简体   繁体   English

在C#中从Excel文件读取数据

[英]Reading data from Excel file in c#

Hi I have an excel file settings.xlsx. 嗨,我有一个excel文件settings.xlsx。 I want to read the data from this file and assign the variables used in my code with the data. 我想从该文件中读取数据,然后将代码中使用的变量分配给该数据。

example

             Column1   Column2
        Row1 Data        500
        Row2 Address     30
        Row3 Value       FPGA 

I have Data,Address and Value as variables in my code. 我的代码中有Data,AddressValue作为变量 Can someone assist me with a pseudocode of c# to open a file and read the contents from it as per my requirement? 有人可以根据我的要求使用c#的伪代码来帮助我打开文件并从文件中读取内容吗? I want to search "Data" word in the excel file and take the value next to the cell containing "Data" and assign it to the variable "Data". 我想在excel文件中搜索“数据”字词,并在包含“数据”的单元格旁边获取值,并将其分配给变量“数据”。 I know it is confusing but I really want the final data to look like something below. 我知道这很令人困惑,但我真的希望最终数据看起来像下面的东西。

Data=500 //Finally I want my variables to have the data as follows
        Address=30
        Value= FPGA  

I tried opening a file in my code.But since I am new to c#,i am not able to understand what is going wrong in my code. 我尝试在代码中打开文件。但是由于我是C#的新手,所以我无法理解代码中出了什么问题。 I am stuck at this point. 我被困在这一点上。 Open function is giving an error. 打开功能出现错误。 Kindly help me. 请帮助我。 I tried to open the excel file in my c# code. 我试图用C#代码打开excel文件。 But somehow it is saying Open function overload method doesn't take one argument. 但是以某种方式说开放函数重载方法不需要一个参数。 How to open and read the file? 如何打开和读取文件?

string Filepath = @Filename;
Excel.Application excelapp = new Excel.Application();
excelapp.Visible = true;
var MyBook = excelapp.Workbooks.Open(Filepath);

It will be really helpful if somone gives a pseudocode for the same. 如果somone提供相同的伪代码,则将非常有帮助。

Hi, I was able to open the file. 您好,我能够打开文件。

string Filepath = Path.Combine(Directory.GetCurrentDirectory(), Filename);
Excel.Application excelapp = new Excel.Application();
excelapp.Visible = true;
var Workbook = excelapp.Workbooks.Open(Filepath, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0,true,1, 0);

var xlWorkSheet = (Excel.Worksheet)Workbook.Worksheets.get_Item(2); var xlWorkSheet =(Excel.Worksheet)Workbook.Worksheets.get_Item(2); Excel.Range range = xlWorkSheet.UsedRange; Excel.Range范围= xlWorkSheet.UsedRange;

But when I try to store the cell value in my variable, it gives me an error. 但是,当我尝试将单元格值存储在变量中时,它给了我一个错误。 I somehow cannot use Cells.value. 我以某种方式不能使用Cells.value。 I tried using the following but not able to store the data. 我尝试使用以下内容,但无法存储数据。 Can anybody help? 有人可以帮忙吗?

uint pbaudRate2 = Convert.ToUInt32(range.Value2.ToString()); uint pbaudRate2 = Convert.ToUInt32(range.Value2.ToString());

为什么cells.value不适合我?

Here is a small demo how to read a range of Excel cells 这是一个小示例,演示如何读取一系列Excel单元格

    //  cf. http://support.microsoft.com/kb/302084/en-us
    Excel.Application XL = new Microsoft.Office.Interop.Excel.Application();
    Excel._Workbook WB = XL.Workbooks.Open(fileName, ReadOnly: true);
    Excel._Worksheet WS = (Excel._Worksheet)WB.Sheets[sheetName];
    Excel.Range R = WS.get_Range(GetAddress(row1, col1), GetAddress(row2, col2));
    object[,] arr = (object[,])R.Value;


    ....

    private string GetAddress(int rowNumber, int columnNumber)
    {
        int dividend = columnNumber;
        string columnName = String.Empty;
        int modulo;

        while (dividend > 0)
        {
            modulo = (dividend - 1) % 26;
            columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
            dividend = (int)((dividend - modulo) / 26);
        }

        return columnName + rowNumber;
    }

The cell values are copied to a 2D array of objects. 单元格值将复制到2D对象数组。 Further processing depends on the value types. 进一步处理取决于值类型。

Note that the transfer of an array is much faster than a nested loop of single cell copy operations. 请注意,数组的传输要比单单元格复制操作的嵌套循环快得多。

If you can make a slight change in your excel file, there is a much easier way to read the data. 如果您可以在excel文件中稍作更改,则有一种更简单的方法来读取数据。 You need to have Column names in the first row (any names will do eg "ColumnName", "ColumnValue"), and data in subsequent rows. 您需要在第一行中具有列名称(任何名称都可以,例如“ ColumnName”,“ ColumnValue”),并在随后的行中具有数据。 Then you can use code like this: 然后,您可以使用如下代码:

string xlConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=yourfullfilepathandname.xlsx;Extended Properties='Excel 8.0;HDR=Yes;';";
var xlConn = new OleDbConnection(xlConnStr);

var da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", xlConn);
var xlDT = new DataTable();
da.Fill(xlDT);

You will now be able to access the values from the DataTable. 现在,您将能够访问DataTable中的值。 In your case: xlDT.Rows[1][1] will hold the value of address (in this case 30). 在您的情况下:xlDT.Rows [1] [1]将保存地址的值(在这种情况下为30)。 One thing to note: numbers in an Excel spreadsheet need to be retrieved as doubles and then cast if you want something else: 需要注意的一件事:Excel电子表格中的数字需要以双精度形式检索,然后在需要其他类型时进行强制转换:

int myAddress = (int)(double)xlDT.Rows[1][1]; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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