简体   繁体   English

在C#中从Excel工作表中读取数据?

[英]Read Data from Excel Worksheet in c#?

I need some way to read worksheets from an Excel file, then select what it's important, and put all the Data in a Database. 我需要某种方式从Excel文件中读取工作表,然后选择重要的内容并将所有数据放入数据库中。

It's a job for one time only. 这只是一次工作。 It's an old excel file with information, that have to be passed to a Database, and which will work with an application that i have developed. 这是一个带有信息的旧excel文件,必须将其传递到数据库,并且该文件可以与我开发的应用程序一起使用。

I saw many examples but i am not understanding well how it works, and which way is the best to do this type of work. 我看到了很多示例,但我不太了解它是如何工作的,以及哪种方式是完成此类工作的最佳方法。

My idea is to develop some application in c# that to this process. 我的想法是在C#中开发一些用于此过程的应用程序。

I've used this before and it works well. 我以前使用过,效果很好。 http://exceldatareader.codeplex.com/ http://exceldatareader.codeplex.com/

had an example handy... 有个方便的例子...

using (FileStream fileStream = File.Open(inputFilenames[0], FileMode.Open, FileAccess.Read))
{
    IExcelDataReader excelReader;
    if (Path.GetExtension(inputFilenames[0]) == ".xls")
        excelReader = Factory.CreateReader(fileStream, ExcelFileType.Binary);
    else
        excelReader = Factory.CreateReader(fileStream, ExcelFileType.OpenXml);

    excelReader.NextResult();
    while (excelReader.Name != this.Worksheet)
        excelReader.NextResult();                

    while (excelReader.Read())
    {
        if (FirstRowHasColumnNames)
        {
            FirstRowHasColumnNames = false;
        }
        else
        {
            //do stuff
            var test = GetColumnData(excelReader, 1);
        }
    }

    this.Save(outputFilename);
}

I strongly suggest using a linq provider to connect to excel. 我强烈建议使用linq提供程序连接到excel。 This should make it very easy to query for the information you are looking for. 这将使查询所需信息变得非常容易。 Once you have it, inserting into the database should be easy. 有了它之后,插入数据库应该很容易。

http://code.google.com/p/linqtoexcel/ http://code.google.com/p/linqtoexcel/

LINQ may work and would be preferable for a relatively simple table. LINQ可能有效,并且对于相对简单的表而言更可取。 A traditional approach would be to use COM Interop. 传统方法是使用COM Interop。 Here's a Microsoft page about to work with Excel using COM interop (it is for spreadsheet creation, but the principles are the same - just use different API methods to open and read data): 这是一个即将通过COM interop与Excel一起使用的Microsoft页面(用于电子表格创建,但是原理是相同的-只是使用不同的API方法来打开和读取数据):

http://msdn.microsoft.com/en-us/library/ms173186(v=vs.80).aspx http://msdn.microsoft.com/en-us/library/ms173186(v=vs.80).aspx

Read Data from Excel Worksheet in c#? 在C#中从Excel工作表中读取数据? I got the Exact solution here visit http://microsoftdotnetsolutions.blogspot.in/2012/12/get-excel-sheet-data.html 我在这里获得了确切的解决方案,请访问http://microsoftdotnetsolutions.blogspot.in/2012/12/get-excel-sheet-data.html

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

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