从 C# 读取 Excel 文件

发布于 2024-07-04 21:31:09 字数 157 浏览 5 评论 0原文

是否有免费或开源库可以直接从 C# 程序读取 Excel 文件 (.xls)?

它不需要太花哨,只需选择一个工作表并将数据作为字符串读取即可。 到目前为止,我一直在使用 Excel 的“导出到 Unicode 文本”功能,并解析生成的(制表符分隔的)文件,但我想消除手动步骤。

Is there a free or open source library to read Excel files (.xls) directly from a C# program?

It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

寄与心 2024-07-11 21:31:10

Take.io Spreadsheet 将为您免费完成这项工作。 只需看看这个

Take.io Spreadsheet will do this work for you, and at no charge. Just take a look at this.

辞别 2024-07-11 21:31:10

我刚刚使用 ExcelLibrary 将 .xls 电子表格加载到数据集中。 对我来说效果很好。

I just used ExcelLibrary to load an .xls spreadsheet into a DataSet. Worked great for me.

静水深流 2024-07-11 21:31:10

我们在相当大的系统中使用ClosedXML

  • 免费
  • 易于安装
  • 直接编码
  • 非常响应支持
  • 开发团队极其乐于接受新建议。 通常新功能和错误修复会在同一周内实施

We use ClosedXML in rather large systems.

  • Free
  • Easy to install
  • Straight forward coding
  • Very responsive support
  • Developer team is extremly open to new suggestions. Often new features and bug fixes are implemented within the same week
超可爱的懒熊 2024-07-11 21:31:10

Excel Package 是一个用于读取/写入 Excel 2007 文件的开源 (GPL) 组件。 我在一个小项目上使用过它,API 很简单。 仅适用于 XLSX (Excel 200&),不适用于 XLS。

源代码似乎组织良好并且易于绕过(如果您需要像我一样扩展功能或修复小问题)。

首先,我尝试了 ADO.Net(Excel 连接字符串)方法,但它充满了令人讨厌的黑客行为 - 例如,如果第二行包含一个数字,它将返回该行中所有字段的整数。下面的列并悄悄删除任何不适合的数据。

Excel Package is an open-source (GPL) component for reading/writing Excel 2007 files. I used it on a small project, and the API is straightforward. Works with XLSX only (Excel 200&), not with XLS.

The source code also seems well-organized and easy to get around (if you need to expand functionality or fix minor issues as I did).

At first, I tried the ADO.Net (Excel connection string) approach, but it was fraught with nasty hacks -- for instance if second row contains a number, it will return ints for all fields in the column below and quietly drop any data that doesn't fit.

下雨或天晴 2024-07-11 21:31:10

SpreadsheetGear 太棒了。 是的,这是一笔费用,但与摆弄这些其他解决方案相比,这是值得的。 它快速、可靠、非常全面,我不得不说,在我的全职软件工作中使用该产品一年半多后,他们的客户支持非常棒!

SpreadsheetGear is awesome. Yes it's an expense, but compared to twiddling with these other solutions, it's worth the cost. It is fast, reliable, very comprehensive, and I have to say after using this product in my fulltime software job for over a year and a half, their customer support is fantastic!

烏雲後面有陽光 2024-07-11 21:31:10

我们使用的解决方案需要:

  • 允许读取/写入 Excel 生成的文件
  • 性能快速(不像使用 COM)
  • 与 MS Office 独立 strong>(无需安装 MS Office 的客户端即可使用)
  • 免费开源(但积极开发)

有多种选择,但我们发现NPoi (Java 长期存在的 Poi 开源项目的 .NET 端口)是最好的:
http://npoi.codeplex.com/

它还允许使用 .doc 和 .ppt 文件格式

The solution that we used, needed to:

  • Allow Reading/Writing of Excel produced files
  • Be Fast in performance (not like using COMs)
  • Be MS Office Independent (needed to be usable without clients having MS Office installed)
  • Be Free or Open Source (but actively developed)

There are several choices, but we found NPoi (.NET port of Java's long existing Poi open source project) to be the best:
http://npoi.codeplex.com/

It also allows working with .doc and .ppt file formats

酒儿 2024-07-11 21:31:10

如果只是表格数据。 我推荐 Marcos Melli 的文件数据助手,可以在此处下载。

If it's just tabular data. I would recommend file data helpers by Marcos Melli which can be downloaded here.

慕巷 2024-07-11 21:31:10

虽然迟到了,但我是 LinqToExcel 的粉丝

Late to the party, but I'm a fan of LinqToExcel

叶落知秋 2024-07-11 21:31:10

您可以编写一个 Excel 电子表格来加载给定的 Excel 电子表格并将其保存为 csv(而不是手动执行)。

然后你可以从 C# 自动化它。

一旦它在 csv 中,c# 程序就可以理解它。

(另外,如果有人要求你用 Excel 编程,最好假装你不知道如何)

(编辑:啊,是的,罗布和瑞安都是对的)

you could write an excel spreadsheet that loads a given excel spreadsheet and saves it as csv (rather than doing it manually).

then you could automate that from c#.

and once its in csv, the c# program can grok that.

(also, if someone asks you to program in excel, it's best to pretend you don't know how)

(edit: ah yes, rob and ryan are both right)

灯下孤影 2024-07-11 21:31:10

我知道人们一直在为此目的制作 Excel“扩展”。
您或多或少在 Excel 中创建一个按钮,显示“导出到程序 X”,然后以程序可以读取的格式导出并发送数据。

http://msdn.microsoft.com/en-us/library/ms186213。 aspx 应该是一个很好的起点。

祝你好运

I know that people have been making an Excel "extension" for this purpose.
You more or less make a button in Excel that says "Export to Program X", and then export and send off the data in a format the program can read.

http://msdn.microsoft.com/en-us/library/ms186213.aspx should be a good place to start.

Good luck

凑诗 2024-07-11 21:31:10

刚刚做了一个快速演示项目,需要管理一些 Excel 文件。 GemBox 软件中的 .NET 组件足以满足我的需求。 它有一个免费版本,但有一些限制。

http://www.gemboxsoftware.com/GBSpreadsheet.htm

Just did a quick demo project that required managing some excel files. The .NET component from GemBox software was adequate for my needs. It has a free version with a few limitations.

http://www.gemboxsoftware.com/GBSpreadsheet.htm

哽咽笑 2024-07-11 21:31:10

不是免费的,但最新的 Office 有一个非常好的自动化 .Net API。 (API 已经存在很长一段时间了,但它是令人讨厌的 COM)您可以在代码中执行您想要/需要的所有操作,而 Office 应用程序仍然是一个隐藏的后台进程。

Not free, but with the latest Office there's a very nice automation .Net API. (there has been an API for a long while but was nasty COM) You can do everything you want / need in code all while the Office app remains a hidden background process.

溺孤伤于心 2024-07-11 21:31:10

如果我在这里偏离基地,请原谅我,但这不是 Office PIA 的用途是什么?

Forgive me if I am off-base here, but isn't this what the Office PIA's are for?

幻想少年梦 2024-07-11 21:31:10

最近,部分是为了更好地使用 LINQ...我一直在使用 Excel 的自动化 API 将文件另存为 XML 电子表格,然后使用 LINQ to XML 处理该文件。

Lately, partly to get better at LINQ.... I've been using Excel's automation API to save the file as XML Spreadsheet and then get process that file using LINQ to XML.

遮云壑 2024-07-11 21:31:10

SpreadsheetGear for .NET 是适用于 .NET 的 Excel 兼容电子表格组件。 您可以在产品页面。 您可以通过免费、功能齐全的评估亲自尝试。

SpreadsheetGear for .NET is an Excel compatible spreadsheet component for .NET. You can see what our customers say about performance on the right hand side of our product page. You can try it yourself with the free, fully-functional evaluation.

旧时模样 2024-07-11 21:31:10

SmartXLS是另一个Excel电子表格组件,它支持Excel图表、公式引擎的大部分功能,并且可以读/写Excel2007 openxml 格式。

SmartXLS is another excel spreadsheet component which support most features of excel Charts,formulas engines, and can read/write the excel2007 openxml format.

最近可好 2024-07-11 21:31:10

.NET 组件 Excel Reader .NET 可能会满足您的要求。 对于读取 XLSX 和 XLS 文件来说已经足够了。 所以尝试一下:

http://www.devtriogroup.com/ExcelReader

The .NET component Excel Reader .NET may satisfy your requirement. It's good enought for reading XLSX and XLS files. So try it from:

http://www.devtriogroup.com/ExcelReader

雨轻弹 2024-07-11 21:31:10

我推荐 FileHelpers 库,它是一个免费且易于使用的 .NET 库,用于从 EXCEL、文件、字符串或流等中的固定长度或分隔记录导入/导出数据。

Excel 数据链接文档部分
http://filehelpers.sourceforge.net/example_exceldatalink.html

I recommend the FileHelpers Library which is a free and easy to use .NET library to import/export data from EXCEL, fixed length or delimited records in files, strings or streams + More.

The Excel Data Link Documentation Section
http://filehelpers.sourceforge.net/example_exceldatalink.html

白昼 2024-07-11 21:31:10

您可以尝试使用这个开源解决方案,它使处理 Excel 变得更加干净。

http://excelwrapperdotnet.codeplex.com/

You can try using this open source solution that makes dealing with Excel a lot more cleaner.

http://excelwrapperdotnet.codeplex.com/

演多会厌 2024-07-11 21:31:10

ExcelMapper 是一个开源工具 (http://code.google.com/p/excelmapper/) 可用于将 Excel 工作表读取为强类型对象。 它支持 xls 和 xlsx 格式。

ExcelMapper is an open source tool (http://code.google.com/p/excelmapper/) that can be used to read Excel worksheets as Strongly Typed Objects. It supports both xls and xlsx formats.

病女 2024-07-11 21:31:10

我想展示一种使用 .NET 读取 xls/xlsx 文件的简单方法。 希望以下内容对您有所帮助。

 private DataTable ReadExcelToTable(string path)    
 {

     //Connection String

     string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";  
     //the same name 
     //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + //";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; 

     using(OleDbConnection conn = new OleDbConnection(connstring))
     {
        conn.Open();
        //Get All Sheets Name
        DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"});  

        //Get the First Sheet Name
        string firstSheetName = sheetsName.Rows[0][2].ToString(); 

        //Query String 
        string sql = string.Format("SELECT * FROM [{0}]",firstSheetName); 
        OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring);
        DataSet set = new DataSet();
        ada.Fill(set);
        return set.Tables[0];   
   }
 }

代码来自文章:http://www. c-sharpcorner.com/uploadfile/d2dcfc/read-excel-file-with-net/。 您可以从中获得更多详细信息。

I want to show a simple method to read xls/xlsx file with .NET. I hope that the following will be helpful for you.

 private DataTable ReadExcelToTable(string path)    
 {

     //Connection String

     string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";  
     //the same name 
     //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + //";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; 

     using(OleDbConnection conn = new OleDbConnection(connstring))
     {
        conn.Open();
        //Get All Sheets Name
        DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"});  

        //Get the First Sheet Name
        string firstSheetName = sheetsName.Rows[0][2].ToString(); 

        //Query String 
        string sql = string.Format("SELECT * FROM [{0}]",firstSheetName); 
        OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring);
        DataSet set = new DataSet();
        ada.Fill(set);
        return set.Tables[0];   
   }
 }

Code is from article: http://www.c-sharpcorner.com/uploadfile/d2dcfc/read-excel-file-with-net/. You can get more details from it.

人心善变 2024-07-11 21:31:09

Koogra 是一个用 C# 编写的开源组件,用于读取和写入 Excel 文件。

Koogra is an open-source component written in C# that reads and writes Excel files.

不气馁 2024-07-11 21:31:09

虽然您确实特别要求使用 .xls,这意味着较旧的文件格式,但对于 OpenXML 格式(例如 xlsx),我强烈推荐 OpenXML SDK(http://msdn.microsoft.com/en-us/library/bb448854.aspx)

While you did specifically ask for .xls, implying the older file formats, for the OpenXML formats (e.g. xlsx) I highly recommend the OpenXML SDK (http://msdn.microsoft.com/en-us/library/bb448854.aspx)

零度° 2024-07-11 21:31:09

不久前,我用 C# 读取了很多 Excel 文件,我们使用了两种方法:

  • COM API,您可以直接访问 Excel 的对象并通过方法和属性操作它们
  • ODBC 驱动程序,允许像数据库一样使用 Excel。

后一种方法快得多:通过 COM 读取包含 20 列和 200 行的大表需要 30 秒,通过 ODBC 则需要半秒。 因此,如果您只需要数据,我会推荐数据库方法。

干杯,

卡尔

I did a lot of reading from Excel files in C# a while ago, and we used two approaches:

  • The COM API, where you access Excel's objects directly and manipulate them through methods and properties
  • The ODBC driver that allows to use Excel like a database.

The latter approach was much faster: reading a big table with 20 columns and 200 lines would take 30 seconds via COM, and half a second via ODBC. So I would recommend the database approach if all you need is the data.

Cheers,

Carl

怂人 2024-07-11 21:31:09

Excel 数据阅读器怎么样?

http://exceldatareader.codeplex.com/

我在生产环境中使用了愤怒将大量数据从各种 Excel 文件提取到 SQL Server Compact 中。 它工作得很好而且相当健壮。

How about Excel Data Reader?

http://exceldatareader.codeplex.com/

I've used in it anger, in a production environment, to pull large amounts of data from a variety of Excel files into SQL Server Compact. It works very well and it's rather robust.

绿萝 2024-07-11 21:31:09

这是几年前我使用 .NET 1.1 用 C# 编写的一些代码。 不确定这是否正是您所需要的(并且可能不是我最好的代码:))。

using System;
using System.Data;
using System.Data.OleDb;

namespace ExportExcelToAccess
{
    /// <summary>
    /// Summary description for ExcelHelper.
    /// </summary>
    public sealed class ExcelHelper
    {
        private const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\"Excel 8.0;HDR=Yes;\";";

        public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName)
        {
            OleDbConnection objConnection = new OleDbConnection();
            objConnection = new OleDbConnection(CONNECTION_STRING.Replace("<FILENAME>", fullFileName));
            DataSet dsImport = new DataSet();

            try
            {
                objConnection.Open();

                DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )
                {
                    //raise exception if needed
                }

                if( (null != sheetName) && (0 != sheetName.Length))
                {
                    if( !CheckIfSheetNameExists(sheetName, dtSchema) )
                    {
                        //raise exception if needed
                    }
                }
                else
                {
                    //Reading the first sheet name from the Excel file.
                    sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
                }

                new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", objConnection ).Fill(dsImport);
            }
            catch (Exception)
            {
                //raise exception if needed
            }
            finally
            {
                // Clean up.
                if(objConnection != null)
                {
                    objConnection.Close();
                    objConnection.Dispose();
                }
            }


            return dsImport.Tables[0];
            #region Commented code for importing data from CSV file.
            //              string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=" + System.IO.Path.GetDirectoryName(fullFileName) +";" +"Extended Properties=\"Text;HDR=YES;FMT=Delimited\"";
            //
            //              System.Data.OleDb.OleDbConnection conText = new System.Data.OleDb.OleDbConnection(strConnectionString);
            //              new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(fullFileName).Replace(".", "#"), conText).Fill(dsImport);
            //              return dsImport.Tables[0];

            #endregion
        }

        /// <summary>
        /// This method checks if the user entered sheetName exists in the Schema Table
        /// </summary>
        /// <param name="sheetName">Sheet name to be verified</param>
        /// <param name="dtSchema">schema table </param>
        private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema)
        {
            foreach(DataRow dataRow in dtSchema.Rows)
            {
                if( sheetName == dataRow["TABLE_NAME"].ToString() )
                {
                    return true;
                }   
            }
            return false;
        }
    }
}

Here's some code I wrote in C# using .NET 1.1 a few years ago. Not sure if this would be exactly what you need (and may not be my best code :)).

using System;
using System.Data;
using System.Data.OleDb;

namespace ExportExcelToAccess
{
    /// <summary>
    /// Summary description for ExcelHelper.
    /// </summary>
    public sealed class ExcelHelper
    {
        private const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\"Excel 8.0;HDR=Yes;\";";

        public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName)
        {
            OleDbConnection objConnection = new OleDbConnection();
            objConnection = new OleDbConnection(CONNECTION_STRING.Replace("<FILENAME>", fullFileName));
            DataSet dsImport = new DataSet();

            try
            {
                objConnection.Open();

                DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )
                {
                    //raise exception if needed
                }

                if( (null != sheetName) && (0 != sheetName.Length))
                {
                    if( !CheckIfSheetNameExists(sheetName, dtSchema) )
                    {
                        //raise exception if needed
                    }
                }
                else
                {
                    //Reading the first sheet name from the Excel file.
                    sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
                }

                new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", objConnection ).Fill(dsImport);
            }
            catch (Exception)
            {
                //raise exception if needed
            }
            finally
            {
                // Clean up.
                if(objConnection != null)
                {
                    objConnection.Close();
                    objConnection.Dispose();
                }
            }


            return dsImport.Tables[0];
            #region Commented code for importing data from CSV file.
            //              string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=" + System.IO.Path.GetDirectoryName(fullFileName) +";" +"Extended Properties=\"Text;HDR=YES;FMT=Delimited\"";
            //
            //              System.Data.OleDb.OleDbConnection conText = new System.Data.OleDb.OleDbConnection(strConnectionString);
            //              new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(fullFileName).Replace(".", "#"), conText).Fill(dsImport);
            //              return dsImport.Tables[0];

            #endregion
        }

        /// <summary>
        /// This method checks if the user entered sheetName exists in the Schema Table
        /// </summary>
        /// <param name="sheetName">Sheet name to be verified</param>
        /// <param name="dtSchema">schema table </param>
        private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema)
        {
            foreach(DataRow dataRow in dtSchema.Rows)
            {
                if( sheetName == dataRow["TABLE_NAME"].ToString() )
                {
                    return true;
                }   
            }
            return false;
        }
    }
}
葬シ愛 2024-07-11 21:31:09

这是我在 Excel 2003 中使用的:

Dictionary<string, string> props = new Dictionary<string, string>();
props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
props["Data Source"] = repFile;
props["Extended Properties"] = "Excel 8.0";

StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> prop in props)
{
    sb.Append(prop.Key);
    sb.Append('=');
    sb.Append(prop.Value);
    sb.Append(';');
}
string properties = sb.ToString();

using (OleDbConnection conn = new OleDbConnection(properties))
{
    conn.Open();
    DataSet ds = new DataSet();
    string columns = String.Join(",", columnNames.ToArray());
    using (OleDbDataAdapter da = new OleDbDataAdapter(
        "SELECT " + columns + " FROM [" + worksheet + "$]", conn))
    {
        DataTable dt = new DataTable(tableName);
        da.Fill(dt);
        ds.Tables.Add(dt);
    }
}

This is what I used for Excel 2003:

Dictionary<string, string> props = new Dictionary<string, string>();
props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
props["Data Source"] = repFile;
props["Extended Properties"] = "Excel 8.0";

StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> prop in props)
{
    sb.Append(prop.Key);
    sb.Append('=');
    sb.Append(prop.Value);
    sb.Append(';');
}
string properties = sb.ToString();

using (OleDbConnection conn = new OleDbConnection(properties))
{
    conn.Open();
    DataSet ds = new DataSet();
    string columns = String.Join(",", columnNames.ToArray());
    using (OleDbDataAdapter da = new OleDbDataAdapter(
        "SELECT " + columns + " FROM [" + worksheet + "$]", conn))
    {
        DataTable dt = new DataTable(tableName);
        da.Fill(dt);
        ds.Tables.Add(dt);
    }
}
前事休说 2024-07-11 21:31:09

如果只是 Excel 文件中包含的简单数据,您可以通过 ADO.NET 读取数据。 请参阅此处列出的连接字符串:

http://www.connectionstrings.com/?rier=excel2007
或者
http://www.connectionstrings.com/?rier=excel

-Ryan

更新:那么你可以通过类似 select * from [Sheet1$] 之类的方式读取工作表

If it is just simple data contained in the Excel file you can read the data via ADO.NET. See the connection strings listed here:

http://www.connectionstrings.com/?carrier=excel2007
or
http://www.connectionstrings.com/?carrier=excel

-Ryan

Update: then you can just read the worksheet via something like select * from [Sheet1$]

千柳 2024-07-11 21:31:09

ADO.NET 方法既快速又简单,但它有一些您应该注意的怪癖,特别是关于如何处理数据类型的怪癖。

这篇优秀的文章将帮助您避免一些常见的陷阱:
http://blog.lab49.com/archives/196

The ADO.NET approach is quick and easy, but it has a few quirks which you should be aware of, especially regarding how DataTypes are handled.

This excellent article will help you avoid some common pitfalls:
http://blog.lab49.com/archives/196

流殇 2024-07-11 21:31:09
var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();

adapter.Fill(ds, "anyNameHere");

DataTable data = ds.Tables["anyNameHere"];

这是我通常使用的。 它有点不同,因为我通常在表的编辑处粘贴 AsEnumerable():

var data = ds.Tables["anyNameHere"].AsEnumerable();

因为这让我可以使用 LINQ 从字段中搜索和构建结构。

var query = data.Where(x => x.Field<string>("phoneNumber") != string.Empty).Select(x =>
                new MyContact
                    {
                        firstName= x.Field<string>("First Name"),
                        lastName = x.Field<string>("Last Name"),
                        phoneNumber =x.Field<string>("Phone Number"),
                    });
var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();

adapter.Fill(ds, "anyNameHere");

DataTable data = ds.Tables["anyNameHere"];

This is what I usually use. It is a little different because I usually stick a AsEnumerable() at the edit of the tables:

var data = ds.Tables["anyNameHere"].AsEnumerable();

as this lets me use LINQ to search and build structs from the fields.

var query = data.Where(x => x.Field<string>("phoneNumber") != string.Empty).Select(x =>
                new MyContact
                    {
                        firstName= x.Field<string>("First Name"),
                        lastName = x.Field<string>("Last Name"),
                        phoneNumber =x.Field<string>("Phone Number"),
                    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文