[英]Reading from Excel File
I have seen many examples of this around but something isn't working for me. 我已经看到了很多这样的例子,但是有些东西对我没有用。
What I am looking to do is to read an Excel sheet, given a sheet and store those values into Lists. 我想要做的是阅读一张Excel工作表(给定工作表)并将这些值存储到列表中。
For example, say I have an excel file that looks like: 例如,假设我有一个如下所示的excel文件:
First Second Third
f1 s1 t1
f2 s2 t2
f3 s3 t3
Each row is to be considered a set of values. 每行应视为一组值。
This is what I have doing so far: 到目前为止,这是我所做的:
List<string> ColumnNames= GetColumnNames();
using (OleDbConnection OleDbConn = new OleDbConnection(Path))
{
OleDbConn.Open();
String cmdString = "SELECT * FROM [" + sheetName+ "]";
OleDbCommand cmd = new OleDbCommand(cmdString, OleDbConn);
DataTable dt = new DataTable();
List<ValueSet> sets = new List<ValueSet>();
Dictionary<string, Value> values = new Dictionary <string,value>()
ValueSet valueset = new ValueSet(null);
using (OleDbDataReader oleRdr = cmd.ExecuteReader())
{
while (oleRdr.Read())
{
for (int i = 0; i < ColumnNames.Count; i++)
{
ColumnName cn = new ColumnName(columnNames[i]);
string data= oleRdr[f.Name].ToString();
Value value = new Value(data, f);
if (!values.ContainsKey(ColumnNames[i]))
{
values.Add(ColumnNames[i], value);
}
else
{
values[ColumnNames[i]] = value;
}
}
valueSet= new ValueSet(values);
sets.Add(valueSet);
}
return sets;;
}
I've gotten weird results with certain files using an OleDbConnection
. 使用
OleDbConnection
对于某些文件我得到了奇怪的结果。
I suggest http://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F 我建议http://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F
With this you can read your CSV into a datatable and parse it into a list as follows: 这样,您可以将CSV读入数据表并将其解析为列表,如下所示:
DataTable dtPrereg;
using (GenericParserAdapter gp = new GenericParserAdapter(Server.MapPath("prereg.csv"), Encoding.UTF8))
{
gp.FirstRowHasHeader = true;
dtPrereg = gp.GetDataTable();
}
I haven't tested this on tab delimited files, but it should work the same (or you could convert your file to CSV) 我尚未在制表符分隔的文件上对此进行过测试,但是它应该可以正常工作(或者您可以将文件转换为CSV)
If you really have a spreadsheet with a known number of named columns and you want to project them into a List<List<string>>
it's a lot easier to just do it with Linq. 如果您确实有一个包含已知数量的命名列的电子表格,并且想将它们投影到
List<List<string>>
,那么使用Linq进行操作会容易得多。
eg 例如
List<List<string>> data;
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
data = (from row in rdr.Cast<DbDataRecord>()
select new List<string>
{
row["First"].ToString(),
row["Second"].ToString(),
row["Third"].ToString()
}).ToList();
}
try changing 尝试改变
ValueSet= new ValueSet(values);
sets.Add(ValueSet);
to 至
valueset = new ValueSet(values);
sets.Add(valueset );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.