首页 > 解决方案 > 更新在 ASP.NET MVC 中上传的 Excel 工作表

问题描述

我有一个函数,其中上传了一个 Excel 工作表,并使用与后端字符串列表中的项目匹配的列名读取单元格。我需要更改列名(删除空格并转换为 lower()),以便在我使用字符串列表作为列名来读取 Excel 工作表时与项目匹配。

我正在使用 nuget 包中的 IExcelDataReader 库。我使用这个包读取了所有列名,并遍历它们试图改变它们,但我不能这样做,因为它是只读模式。

如何更改上传的 Excel 工作表的列名。

          public ActionResult Import(HttpPostedFileBase upload)
          {
              if (upload != null && upload.ContentLength > 0)
                {
                    Stream stream = upload.InputStream;
                    IExcelDataReader reader = null;
                    if (upload.FileName.EndsWith(".xls") || upload.FileName.EndsWith(".xlsx"))
                    {
                        var file = upload.FileName;
                        reader = ExcelDataReader.ExcelReaderFactory.CreateReader(stream);
                        var conf = new ExcelDataSetConfiguration
                        {
                            ConfigureDataTable = _ => new ExcelDataTableConfiguration
                            {
                                UseHeaderRow = true
                            }
                        };
                        var dataSet = reader.AsDataSet(conf);                            

                        var Model = dataSet.Tables[0].Rows;
                        var meta = listOfStrings; // Column names to be read in a list 
                            for (int i = 0; i < Model.Count; i++)
                            {
                                var dict = new Dictionary<string, string>();
                                foreach (var item in meta)
                                {
                                    dict.Add(item, Model[i][item.ToLower().Trim()].ToString());
                                    // During this stage I need the column names to exactly match my list of string                         
                                   // What can I do to Convert my strings to lower case and trim them?
                                }
                             }
                    }
                 }
             }

标签: c#asp.netexcelasp.net-mvc-5upload

解决方案


推荐阅读