SoFunction
Updated on 2025-03-06

C# Read Excel content example sharing


using System;
using ;
using ;
using ;
using ;
using ;
using Excel = ;
using ;

namespace ReadExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"D:\TransferPlant\";
            DataTable dt = ExcelToDataSet(fileName);
            if ( > 0)
            {
                for (int i = 0; i < ; i++)
                {
                    ([i][0].ToString());
                }
            }
        }

        static public DataTable ExcelToDataSet(string filename)
        {
            string strCon = " Provider = .4.0 ; Data Source = "+filename+";Extended Properties=Excel 8.0";
            OleDbConnection conn = new OleDbConnection(strCon);
            ();
//Return to Excel's schema, including the name, type, creation time and modification time of each sheet table, etc.
            DataTable dtSheetName = (, new object[] { null, null, null, "Table" });
//Array of strings containing table names in excel
            string[] strTableNames = new string[];
            for (int k = 0; k < ; k++)
            {
                strTableNames[k] = [k]["TABLE_NAME"].ToString();
            }
            OleDbDataAdapter myCommand = null;
            DataTable dt = new DataTable();
//Query data from the specified indication, you can first list all indications for user selection
            string strExcel = "select * from [" + strTableNames[0] + "]";
            myCommand = new OleDbDataAdapter(strExcel, strCon);
            (dt);

            return dt;
        }
    }
}