سؤال

I am new to c# and am trying to read an XLSX file in c# with the following code:

string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=c:\\Temp\\source.xlsx;Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";

//code to read the content of format file 
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();

DataTable dt = new DataTable();
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Tabelle1$]", con);

myCommand.Fill(dt);
Console.Write(dt.Rows.Count);

I get t a correct count from the output, but I have 2 more questions:

1.How do make a select where statement (how to access the rows)?

 select * from [Tabelle1$] where A = '123' (A being an existing Excel row)

will throw an error mentioning wrong parameters...

2.can anyone supply me with a tutorial link or short sample how to access the data?

هل كانت مفيدة؟

المحلول

Please refer the following sample code:

private DataTable LoadXLS(string strFile, String sheetName, String column, String value)
{
    DataTable dtXLS = new DataTable(sheetName);

    try
    {
       string strConnectionString = "";

       if(strFile.Trim().EndsWith(".xlsx")) {

           strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);

       } else if(strFile.Trim().EndsWith(".xls")) {

           strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);

       }

       OleDbConnection SQLConn = new OleDbConnection(strConnectionString);

       SQLConn.Open();

       OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();

       string sql = "SELECT * FROM [" + sheetName + "$] WHERE " + column + " = " + value;

       OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);

       SQLAdapter.SelectCommand = selectCMD;

       SQLAdapter.Fill(dtXLS);

       SQLConn.Close();
    }

    catch (Exception e)
    {
       Console.WriteLine(e.ToString());
    }

    return dtXLS;

}

نصائح أخرى

Personally, I have found reading Excel spreadsheets with OleDbConnections difficult to work with; thus I would like to offer a great open-source & free ExcelMapper alternative.

It provides a much more concise (ie readable) way of reading Excel Files compared to OLE queries.

1. Given an Excel File:

enter image description here

2.Create a Person C# object:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

3.Read it using ExcelMapper

  var fileName = @"C:\Temp\Names.xlsx"; // your excel file
  List<Person> people = new ExcelMapper(fileName).Fetch<Person>();

You can also read from other worksheets, by simply passing in an additional sheet argument:

  var fileName = @"C:\Temp\Names.xlsx"; // your excel file
  List<Person> people = new ExcelMapper(fileName).Fetch<Person>("Sheet2");

You can install it using NuGet

Install-Package ExcelMapper

Disclaimer: I am not associated with ExcelMapper, but after trying various different libraries, I found this library the easiest to work with.

Reg: "2.can anyone supply me with a tutorial link or short sample how to access the data"

Here is a short video showcasing the above.

instructional video - how to read excel files in c#

I know this is an old question with a great answer but this page came up high on google's results for "import xlsx c#" so I wanted to add a more modern and simpler way to read xls/xlsx data using the NPOI library. I want to make sure new c# developers know that there is an easier way to import Excel data rather than using ado.net.

I use a combination of NPOI and Npoi.Mapper (from donnytian: https://github.com/donnytian/Npoi.Mapper) to import Excel files with ease. Add a nuget reference to NPOI and Npoi.Mapper and then you can import xls/xlsx data using strongly typed classes that correlate directly to the columns that you want to import.

```using System.IO; using System.Linq; using Npoi.Mapper; using Npoi.Mapper.Attributes; using NPOI.SS.UserModel; using UserManagementService.Models;

namespace JobCustomerImport.Processors { public class ExcelEmailProcessor { private UserManagementServiceContext DataContext { get; }

    public ExcelEmailProcessor(int customerNumber)
    {
        DataContext = new UserManagementServiceContext();
    }

    public void Execute(string localPath, int sheetIndex)
    {
        IWorkbook workbook;
        using (FileStream file = new FileStream(localPath, FileMode.Open, FileAccess.Read))
        {
            workbook = WorkbookFactory.Create(file);
        }

        var importer = new Mapper(workbook);
        var items = importer.Take<MurphyExcelFormat>(sheetIndex);
        foreach(var item in items)
        {
            var row = item.Value;
            if (string.IsNullOrEmpty(row.EmailAddress))
                continue;

            UpdateUser(row);
        }

        DataContext.SaveChanges();
    }

    private void UpdateUser(MurphyExcelFormat row)
    {
        //LOGIC HERE TO UPDATE A USER IN DATABASE...
    }

    private class MurphyExcelFormat
    {
        [Column("District")]
        public int District { get; set; }

        [Column("DM")]
        public string FullName { get; set; }

        [Column("Email Address")]
        public string EmailAddress { get; set; }

        [Column(3)]
        public string Username { get; set; }

        public string FirstName
        {
            get
            {
                return Username.Split('.')[0];
            }
        }

        public string LastName
        {
            get
            {
                return Username.Split('.')[1];
            }
        }
    }
}

} ```

If you're interested, I've covered some of the finer points on my blog: How to easily import excel files.

Thanks! Dan

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top