如何在列表中存储Excel文件数据

时间:2017-09-28 13:30:51

标签: c#-4.0

创建应用程序以读取excel(.xls)文件。 我能够读取文件,但它只显示数据的数量。 但无法从文件中获取数据。

Microsoft.Office.Interop.Excel.Application xlApp = new Excel.Application();
                Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Landingfolder\file.xls");
                Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
                Excel.Range xlRange = xlWorksheet.UsedRange;
                int rowCount = xlRange.Rows.Count;
                int colCount = xlRange.Columns.Count;

                for (int i = 1; i <= rowCount; i++)
                {
                    for (int j = 1; j <= colCount; j++)
                    {
                        //new line
                        if (j == 1)
                            Console.Write("\r\n");

                        //write the value to the console
                        if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
                            Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
                        Console.ReadLine();


                    }
                }

请告诉我正确的流程。

1 个答案:

答案 0 :(得分:1)

使用此代码

using System.Data.OleDb;
using System.IO;
using System.Data;

public class Employee
    {
        public string Name { get; set; }

        public string Designation { get; set; }

        public int?  Experience { get; set; }
    }


/// <summary>
        /// Open Connection
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private  OleDbConnection  OpenConnection(string  path)
        {
             OleDbConnectio n  oledbConn  = null;
             try
             {
                 if (Path.GetExtension(path) == ".xls")
                    oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + 

"; Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=2\"");
                else if (Path.GetExtension(path)  == ".xlsx")
                    oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + 

path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");

                oledbConn.Open();
            }
            catch (Exception ex)
            {
                //Error
            }
            return oledbConn;
        }


/// <summary>
        /// Extract 'Service Information' sheet
        /// </summary>
        /// <param name="oledbConn"></param>
        private IList<Employee> ExtractEmployeeExcel(OleDbConnection oledbConn)
        {
            OleDbCommand cmd = new OleDbCommand (); ;
            OleDbDataAdapter oleda = new OleDbDataAdapter();
            DataSet dsEmployeeInfo = new DataSet ();

            cmd.Connection  = oledbConn;
            cmd.CommandT ype = CommandType.Text;
            cmd.CommandT ext = "SELECT * FROM [Employee$]"; //Excel Sheet Name ( Employee )
            oleda = new OleDbDataAdapter(cmd);
            oleda.Fill (dsEmployeeInfo, "Employee");

            var dsEm ployeeInfoList = dsEmployeeInfo.Tables[0].AsEnumerable().Select (s => new Employee
            {
                Name = Convert.ToString(s["Name"] ! = DBNull.Value ? s["Name"] : ""),
                Designation = Convert.ToString(s["Designation"] ! = DBNull.Value ? s["Designation"] : ""),
                Experience = Convert.ToInt32(s["Experience"])
            }).ToList ();

            return dsEmployeeInfoList;
        }

 /// <summary>
        /// Read excel sheet with the user path
        /// </summary>
        /// <param name="path"></param>
        public IList<Employee> ReadExcel(string path)
        {
            IList<Employ ee> objEmployeeInfo = new List<Employee>();
            try
             {               
                OleDbConnection oledbConn = OpenConnection(path);
                if (oledbConn.State == ConnectionState.Open)
                {
                    objEmployeeInfo = ExtractEmployeeExcel (oledbConn);
                    oledbConn.Close();
                }
            }
            catch (Exception ex)
            {
                // Error
            }
            return objEmployeeInfo;
        }

使用代码:

这里调用ReadExcel()方法来获取excel内容。

string path = @"D:\Employee.xls";
        IList<Employee> objExcelCon = ReadExcel(path);