C# 3 ways to read Execl files

method 

1. Use OLEDB to read excel files

1.1What are the data connections provided by C#?

        For different .net data providers, ADO.NET uses different Connection objects to connect to the database. These Connections shield us from specific implementation details and provide a unified implementation method.

There are four types of Connection classes: SqlConnection, OleDbConnection, OdbcConnection and OracleConnection.

The object connection of the Sqlconnection class is a SQL Server database;

Objects of the OracleConnection class connect to the Oracle database;

OleDbConneetion connects to databases that support OLE DB, such as Access;

The object connection of the OdbcConnection class supports ODBC databases.

All communication with the database is done through the Connection object.

1.2 Introduction to using OleDbonnection to link various data sources

        The data access objects of ADO.NET include Connection, Command, DataReader and DataAdaper. Since each .NET Data Provider has its own data access object, they are used in similar ways. Here we mainly introduce the use of various data access objects of OLEDB.NET Data Provider.

OleDbConnection object

In data access, a physical connection to the database must first be established. OLEDB.NET Data Provider uses objects of the OleDbConnection class to identify the physical connection to a database.

Common properties of the OledbConnection class
Attributes illustrate
ConnectionString  Gets or sets the string used to open the database
ConnectionTimeOut Gets the time to wait before terminating the attempt and generating an error when trying to establish a connection
Database Get the current database or the name of the database to be used after the connection is opened
DataSource Get the server name or file name of the data source
Provider Gets the name of the OLEDB provider specified in the "Provider=" clause of the connection string
State Get the current status of the connection
Common methods of OleDbConnection class
method illustrate
Open Open a database connection using the property settings specified by ConnectionString
Close  Close the connection to the database, this is the preferred method of closing any open connection
CreateCommand Creates and returns an OleDbCommand object associated with the OleDbConnection
ChangeDatabase Change the current database for an open OleDbConnection

 1.3 Establish connection string ConnectionString

1. Directly establish the connection string

The way to directly establish a connection string is to first create an OleDbConnection object and set its ConnectionString property as follows:

Provider = Microsoft.Jet.OLEDB.4.0;Data Source = Access database;UserId = username;Password = password;

  Among them, Provider and DataSource are required. If the Access database does not have a password, UserId and Password can be omitted. Since the Access database is a file-based database, the property value of the Data Source should be converted to the absolute path of the server in the actual project. Finally, use the Open method to open the connection.

1.4 Code

        public DataSet ReadExcelToDataSet(string path)
        {
            //连接字符串
            /* 备注:
            	添加 IMEX=1 表示将所有列当做字符串读取,实际应该不是这样,
            	系统默认会查看前8行如果有字符串,则该列会识别为字符串列。
            	如果前8行都是数字,则还是会识别为数字列,日期也一样;
            	如果你觉得8行不够或者太多了,则只能修改注册表HKEY_LOCAL_MACHINE/Software/Microsoft/Jet/4.0/Engines/Excel/TypeGuessRows,
            	如果此值为0,则会根据所有行来判断使用什么类型,通常不建议这麽做,除非你的数据量确实比较少
            */
            string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;IMEX=1';";

            using (OleDbConnection conn = new OleDbConnection(connstring))
            {
                conn.Open();
                System.Data.DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });//存放所有的sheet
                DataSet set = new DataSet();
                for (int i = 0; i < sheetsName.Rows.Count; i++)
                {
                    string sheetName = sheetsName.Rows[i][2].ToString();
                    string sql = string.Format("SELECT * FROM [{0}]", sheetName);
                    OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);

                    ada.Fill(set);
                    set.Tables[i].TableName = sheetName;
                }

                return set;

            }
        }

2. Use the library that comes with Office

2.1 Installation library

2.2 Code

        //2 ,使用Office自带的库
        public System.Data.DataSet GetExcelData(string excelFilePath)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Sheets sheets;
            Microsoft.Office.Interop.Excel.Workbook workbook = null;
            object oMissiong = System.Reflection.Missing.Value;

            DataSet dataSet = new DataSet();
            string cellContent;
            try
            {
                if (app == null)
                {
                    return null;
                }
                workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong,
                    oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);

                sheets = workbook.Worksheets;
                for (int p = 1; p <= sheets.Count; p++)
                {
                    System.Data.DataTable dt = new System.Data.DataTable();
                    Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(p);//读取第一张表

                    for (int j = 1; j <= workSheet.UsedRange.Columns.Count; j++)
                    {

                        Range _range = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, j];
                        if (_range.Text.ToString().Trim() == "")
                            dt.Columns.Add("EQUIPMENT");
                        else
                            dt.Columns.Add(_range.Text.ToString().Trim());

                    }
                    for (int i = 2; i <= workSheet.UsedRange.Rows.Count; i++)
                    {
                        DataRow dr = dt.NewRow();
                        for (int j = 1; j <= workSheet.UsedRange.Columns.Count; j++)
                        {
                            Range _range = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[i, j];
                            cellContent = (_range.Value2 == null) ? "" : _range.Text.ToString().Trim();
                            dr[j - 1] = cellContent;
                        }
                        dt.Rows.Add(dr);
                    }
                    dataSet.Tables.Add(dt);
                }
            }
            finally
            {
                workbook.Close(false, oMissiong, oMissiong);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                workbook = null;
                app.Workbooks.Close();
                app.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                app = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return dataSet;
        }

3. Use ExcelDataReader to read excel files

3.1 Installation library

 3.2 Code

        //3,利用ExcelDataReader 读取excel文件
        public DataSet ReadExcelToDataSet1(string fileNmaePath)
        {
            FileStream stream = null;
            IExcelDataReader excelReader = null;
            DataSet dataSet = null;
            try
            {
                //stream = File.Open(fileNmaePath, FileMode.Open, FileAccess.Read);
                stream = new FileStream(fileNmaePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            }
            catch
            {
                return null;
            }
            string extension = Path.GetExtension(fileNmaePath);

            if (extension.ToUpper() == ".XLS")
            {
                excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
            }
            else if (extension.ToUpper() == ".XLSX")
            {
                excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
            }
            else
            {
                MessageBox.Show("格式错误");
                return null;

            }
            //dataSet = excelReader.AsDataSet();//第一行当作数据读取
            dataSet = excelReader.AsDataSet(new ExcelDataSetConfiguration()
            {
                ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                {
                    UseHeaderRow = true
                }
            });//第一行当作列名读取
            excelReader.Close();
            return dataSet;
        }

result

references

c# Read Excel table data_c# Read excel file content-CSDN Blog

https://www.cnblogs.com/vaevvaev/p/6873367.html

Guess you like

Origin blog.csdn.net/qq_39397927/article/details/133297679