欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#读取excel文件

程序员文章站 2022-05-01 17:44:38
...

C#读取excel文件

   最近在项目中应用到读取excel文件的功能,在此总结一下开发经验。

   读取数据分为两种情况,一种是csv格式的文件,另一种是xlsx格式的文件。

首先需要注意的是:csv文件是以英文逗号间隔的文本文件,而xlsx是电子表格,包含文本、数值、公式和格式。

代码示例:

 

读取csv文件

public class StudentEntity {
            public String name;
            public String no;
            public String fileName;
        }
        public String ReadCsvFileToEntityList(string filePath, String fileName, List<StudentEntity> stuList)
        {
            LoadUtil util = new LoadUtil();
            String result = "S";
            int i = 0;
            try
            {
                String fileAllName = filePath + @"\" + fileName;
                using (StreamReader sr = new StreamReader(fileAllName, Encoding.Default))
                {
                    String line;
                    // 构造解析器
                    SeperatorBasedParser parser = new SeperatorBasedParser(seperator: SeperatorType.COMMA);
                    // 按行拆解数据文件
                    while (!String.IsNullOrEmpty(line = sr.ReadLine()))
                    {
                        //去掉文件头
                        if (line.Contains("学号"))
                        {
                            continue;
                        }
                        var entity = parser.ParseStringToEntity<StudentEntity>(line);
                        String[] lineList = line.Split(',');//根据英文逗号分隔
                        entity.fileName = fileName;//文件名
                        entity.no = lineList[0];//学号
                        entity.name = lineList[1];//姓名
                        stuList.Add(entity);
                        i++;
                    }
                    Console.WriteLine("Total lines: " + i.ToString());
                    FileLogger.log("LoadManager.ParseFileToEntityList Succeed! " + fileAllName);
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file " + fileName + " could not be read: " + ", error line: " + i.ToString());
                Console.WriteLine(e.Message);
                FileLogger.log(e);
                return null;
            }
            return result;
        }

 读取xlsx文件:

 const string connectStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
        public string ReadXlsxFileToEntityList(string filePath, String fileName, List<StudentEntity> stuList)
        {
            String fileAllName = filePath + "\\" + fileName;
            string result = "S";
            FileInfo fileInfo = new FileInfo(fileAllName);
            try
            {
                DataTable sheetTable = GetSheetTable(fileAllName);

                //只需要取第一个Sheet的sheetName
                string sheetName = sheetTable.Rows[0][2].ToString();

                //读取Excel内容,将excel中的内容存在list中
                DataTable dataTable = GetDataTable(fileAllName, sheetName);
                result = GetFocList(dataTable, fileName, stuList);
            }
            catch (Exception e)
            {
                return "E_" + e.Message;
            }
            return result;
        }
        /// <summary>
        /// 根据文件名称和sheet读取文件内容
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public DataTable GetDataTable(string fileName, string sheetName)
        {
            DataTable dataTable = new DataTable();
            OleDbConnection dbConn = new OleDbConnection(string.Format(connectStr, fileName));

            try
            {
                dbConn.Open();

                OleDbCommand dbCmd = new OleDbCommand();
                dbCmd.Connection = dbConn;
                dbCmd.CommandText = "select * from [" + sheetName + "] ";
                dbCmd.CommandType = CommandType.Text;
                OleDbDataAdapter dbApt = new OleDbDataAdapter(dbCmd);
                dbApt.Fill(dataTable);

            }
            finally
            {
                dbConn.Close();
            }
            return dataTable;
        }
        /// <summary>
        /// 根据文件名称获取文件中所有的sheetname
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public DataTable GetSheetTable(string filePath)
        {
            OleDbCommand dbCmd = new OleDbCommand();
            OleDbConnection dbConn = new OleDbConnection(string.Format(connectStr, filePath));
            DataTable sheetTable = null;
            try
            {
                dbConn.Open();
                //dbTable装载了所有的sheetneame
                sheetTable = dbConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                dbConn.Close();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                dbConn.Close();
            }
            return sheetTable;
        }
        /// <summary>
        /// 将dataTable转换为entityList
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public String GetFocList(DataTable dataTable, String fileName, List<StudentEntity> stuList)
        {
            var result = "S";
            if (dataTable.Rows.Count > 0)
            {
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    try
                    {
                        //不读取文件头
                        if (dataTable.Rows[i][0].ToString().Trim().Contains("学号"))
                        {
                            continue;
                        }
                        StudentEntity entity = new StudentEntity();
                        entity.fileName = fileName;//文件名
                        entity.no = dataTable.Rows[i][0].ToString().Trim();//学号
                        entity.name = dataTable.Rows[i][1].ToString().Trim();//姓名
                        stuList.Add(entity);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(e.Message + "   " + i + "   " + dataTable.Rows[i]);
                    }
                }
            }
            return result;
        }