从Excel(或任何文件)数组列表C# [英] From Excel (or any file) to Array List C#

查看:124
本文介绍了从Excel(或任何文件)数组列表C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出一些数字从Excel数组。
比方说,我有这样的一些数据的Excel文件:

I want to put some numbers from Excel to array. Let's say I have an Excel file with some numbers like this:

23
34
1
3
100
56
45
43
56
4
87
6
89
9

23 34 1 3 100 56 45 43 56 4 87 6 89 9

这是Excel只有一个列(或任何文件)
我希望把这些numers的ArrayList中的作为整数,我不需要的结果作为一个数字,但所有这些数字是在int值。

this is just one column in excel (or any file) And i want to put those numers in arraylist as integer numbers, i dont need the result as one number but all those numbers to be in int value.

任何帮助吗?

推荐答案

假设上述是一个字符串(和源无所谓),你可以做到以下几点:

Assuming that the above is a string (and the source does not matter), you can do the following:

string s = "23 34 1 3 100 56 45 43 56 4 87 6 89 9";
string[] numbers = s.Split(' ');

ArrayList numberList = new ArrayList();
int i;

foreach (String num in numbers)
{
    if (Int32.TryParse(num, out i))
        numberList.Add(i);
    else
        Console.WriteLine("'{0}' is not a number!", num);
}

listBox1.DataSource = numberList;

我建议使用列表< INT方式> 而不是的ArrayList 类型安全

以下code读取Excel工作表的所有值将使用一个数据库连接的数据集。然后,您可以挑选所需要的值:

The following code reads all values from an Excel sheet into a data set using a DB connection. You can then pick the value needed.:

String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1ReadOnly=False\"";

OleDbConnection objConn = new OleDbConnection(sConnectionString);

objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + sheetname + "$]", objConn);

OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;

DataSet dsExcelContent = new DataSet();
objAdapter1.Fill(dsExcelContent);

objConn.Close();

修改

没有指定字符串的确切来源,因此,如果这个问题是关于如何读取文件或如何从Excel US preadsheet导入数据,你或许应该改一下你的问题有点。

EDIT
You did not specify the exact source for the string, so if this question is about how to read a file or how to import data from an Excel spreadsheet, you should probably rephrase your question a little.

编辑2

替换列表< INT方式> 的ArrayList 在OP的愿望(对更好的设计)

EDIT 2
Replaced List<int> by ArrayList on OP's wish (against better design).

编辑3

增加了一个新的生产线,以显示OP如何使用的ArrayList 作为数据源的的ListBox ...

EDIT 3
Added a new line to show the OP how to use the ArrayList as a data source for a ListBox...

修改4

增加了code。使用OLEDB读取Excel工作表。

EDIT 4
Added code to read Excel sheet using OleDB.

这篇关于从Excel(或任何文件)数组列表C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆