C# 读取一个 xslx 文件并转换为 List
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10704582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
read an xslx file and convert to List
提问by Ozkan
I have a xslx file with following data
我有一个包含以下数据的 xslx 文件
www.url.com
www.url.com
www.url.com
www.url.com
www.url.com
www.url.com
www.url.com
www.url.com
...
Like you can see I have only 1 column used and a lot of rows.
I need to read that column from the xslx file somehow and convert it to List<string>.
就像您看到的那样,我只使用了 1 列和很多行。我需要以某种方式从 xslx 文件中读取该列并将其转换为List<string>.
Any help?
有什么帮助吗?
Thanks!
谢谢!
采纳答案by Antonio Bakula
You can use EPPlus, it's simple, something like this :
您可以使用EPPlus,这很简单,如下所示:
var ep = new ExcelPackage(new FileInfo(excelFile));
var ws = ep.Workbook.Worksheets["Sheet1"];
var domains = new List<string>();
for (int rw = 1; rw <= ws.Dimension.End.Row; rw++)
{
if (ws.Cells[rw, 1].Value != null)
domains.Add(ws.Cells[rw, 1].Value.ToString());
}
回答by Matteo Migliore
You can use OOXML to read the file and this library simplify your work http://simpleooxml.codeplex.com.
您可以使用 OOXML 来读取文件,这个库简化了您的工作http://simpleooxml.codeplex.com。
回答by Mike Corcoran
the easiest way is to use OleDb, you can do something like this:
最简单的方法是使用 OleDb,你可以这样做:
List<string> values = new List<string>();
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\your\path\file.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=NO;\"";
using (OleDbConnection conn = new OleDbConnection(constr))
{
conn.Open();
OleDbCommand command = new OleDbCommand("Select * from [SheetName$]", conn);
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
// this assumes just one column, and the value is text
string value = reader[0].ToString();
values.Add(value);
}
}
}
foreach (string value in values)
Console.WriteLine(value);

![创建 c# int[] 值为 0,1,2,3... 长度](/res/img/loading.gif)