C# read excel file

C# read excel file

   Recently, the function of reading excel files has been applied to the project, and the development experience is summarized here.

   There are two cases for reading data, one is a file in csv format, and the other is a file in xlsx format.

First things to note: csv files are comma-separated text files, while xlsx are spreadsheets that contain text, values, formulas, and formatting.

Code example:

 

read csv file

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;
                    // construct parser
                    SeperatorBasedParser parser = new SeperatorBasedParser(seperator: SeperatorType.COMMA);
                    // Disassemble the data file by line
                    while (!String.IsNullOrEmpty(line = sr.ReadLine()))
                    {
                        // remove the file header
                        if (line.Contains("学号"))
                        {
                            continue;
                        }
                        var entity = parser.ParseStringToEntity<StudentEntity>(line);
                        String[] lineList = line.Split(',');//Separate according to English commas
                        entity.fileName = fileName;//File name
                        entity.no = lineList[0];//Student number
                        entity.name = lineList[1];//Name
                        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;
        }

 Read xlsx file:

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);

                //Only need to take the sheetName of the first Sheet
                string sheetName = sheetTable.Rows[0][2].ToString();

                //Read the contents of Excel and store the contents of Excel in the list
                DataTable dataTable = GetDataTable(fileAllName, sheetName);
                result = GetFocList(dataTable, fileName, stuList);
            }
            catch (Exception e)
            {
                return "E_" + e.Message;
            }
            return result;
        }
        /// <summary>
        /// Read the file content according to the file name and 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>
        /// Get all sheetnames in the file according to the file name
        /// </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 loads all 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>
        /// Convert dataTable to 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
                    {
                        // don't read the file header
                        if (dataTable.Rows[i][0].ToString().Trim().Contains("学号"))
                        {
                            continue;
                        }
                        StudentEntity entity = new StudentEntity();
                        entity.fileName = fileName;//File name
                        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;
        }

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326992544&siteId=291194637