read excel data line by line with c# .net

后端 未结 4 457
不思量自难忘°
不思量自难忘° 2020-12-30 09:00

Does anyone know how can I read an excel file line by line in c#.

I found this code which will return the data from excel and display a grindview in c#. However, I j

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 09:20

    You must try this

            string connectionString = "";
            string strFileType = "Type";
            string path = @"C:\Users\UserName\Downloads\";
            string filename = "filename.xls";
            if (fielname.Contains(.xls))
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + filename + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }
            else if (fielname.Contains(.xlsx)
            {
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + filename + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }
    
    
            string query = "SELECT * FROM [SheetName$]";
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand command = new OleDbCommand(query, connection);
    
                connection.Open();
                OleDbDataReader reader = command.ExecuteReader();
    
                var lines = new List();
                while (reader.Read())
                {
                    var fieldCount = reader.FieldCount;
    
                    var fieldIncrementor = 1;
                    var fields = new List();
                    while (fieldCount >= fieldIncrementor)
                    {
                        fields.Add(reader[fieldIncrementor - 1].ToString());
                        fieldIncrementor++;
                    }
    
                    lines.Add(string.Join("\t", fields));
                }
                reader.Close();
            }
    

提交回复
热议问题