【问题标题】:How do i use LinqToExcel to get cell values contained in the excel file如何使用 LinqToExcel 获取 excel 文件中包含的单元格值
【发布时间】:2011-09-07 09:20:46
【问题描述】:

我正在使用此代码检索收件人姓名和收件人号码,但 recpt.receipient_name 和 recpt.receipient_number 为空。

excel表格就是这种格式

姓名编号

安德鲁 1223

詹姆斯 12223

戴夫 454545

//select names from the excel file with specified sheet name
var receipients = from n in messages.Worksheet<BulkSmsModel>(sheetName)
                  select n;

foreach (var recpt in receipients)
{
    BulkSms newRecpt = new BulkSms();

    if (recpt.receipient_number.Equals("") == true || recpt.receipient_number == 0)
    {
        continue;
    }

    newRecpt.receipient_name = recpt.receipient_name;
    newRecpt.receipient_number = Int32.Parse(recpt.receipient_number.ToString());

    IBsmsRepo.insertReceipient(newRecpt);
    IBsmsRepo.save();
}

【问题讨论】:

  • 您对电子表格中的内容一无所知,因此这些列的特定行可能没有数据
  • 电子表格中有数据。它包含两个命名的标题(名称和数字),在这些标题下是各种名称和相应的数字
  • 那么收件人中有多少个项目,如果有多个,那么所有这些属性都为空吗?
  • 是的,收件人的所有 10 行中的属性都为空
  • @plasteezy:您能否在您的问题中添加一张图片,说明表格的结构?并向我们​​展示 BulkSmsModel 和 BulkSms 的代码

标签: asp.net-mvc c#-4.0 linq-to-excel


【解决方案1】:

经过一番研究,我找到了一种使用 LinqToExcel 从 excel 文件中获取值并获取所有单元格列表的方法。检查此 MVC C# 示例。

using LinqToExcel;
using Syncfusion.Olap.Reports;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace YourProject.Controllers
{
    public class DefaultController : Controller
    {
        // GET: Default1
        public ActionResult Index()
        {
            return View();
        }
        public dynamic UploadExcel(HttpPostedFileBase FileUpload)
        {
            string PathToyurDirectory = ConfigurationManager.AppSettings["Path"].ToString();//This can be  in Anywhere, but you have to create a variable in WebConfig AppSettings like this  <add key="Path" value="~/Doc/"/> This directory in my case is inside App whereI upload the files here, and  I Delete it  after use it ; 
           if (FileUpload.ContentType == "application/vnd.ms-excel"
                            || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                            || FileUpload.ContentType == "application/vnd.ms-excel.sheet.binary.macroEnabled.12"
                            )
            {
                string filename = FileUpload.FileName;
                string PathToExcelFile = Server.MapPath(PathToyurDirectory + filename);
                //   string targetpath = ;
                FileUpload.SaveAs(PathToyurDirectory);
                var connectionString = string.Empty;
                string sheetName = string.Empty;
                yourmodel db = new yourmodel();
                Employee Employee = New Employee(); //This is your class no matter What. 
                try
                {

                    if (filename.EndsWith(".xls") || filename.EndsWith(".csv") || filename.EndsWith(".xlsx") || filename.EndsWith(".xlsb"))
                    {

                        connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", PathToExcelFile);
                        sheetName = GetTableName(connectionString);
                    }
                    var ExcelFile = new ExcelQueryFactory(PathToExcelFile);
                    var Data = ExcelFile.Worksheet(sheetName).ToList();

                    foreach (var item in Data)
                    {
                        //if yout excel file does not meet the class estructure.
                        Employee = new Employee
                        {

                            Name = item[1].ToString(),
                            LastName = item[2].ToString(),
                            Address = item[3].ToString(),
                            Phone = item[4].ToString(),
                            CelPghone = item[5].ToString()
                        };
                         db.Employee.Add(Employee);
                        db.SaveChanges();
                    }
                }
                catch (Exception)
                {
                    throw;
                }

            }

            return View();
        }

        private string GetTableName(string connectionString)
        {
            //  You can return all Sheets for a Dropdown if you want to, for me, I just want the first one; 
            OleDbConnection oledbconn = new OleDbConnection(connectionString);
            oledbconn.Open();
            // Get the data table containg the schema guid.
            var dt = oledbconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            var sheet = dt.Rows[0]["TABLE_NAME"].ToString().Replace("$", string.Empty);
            oledbconn.Close();
            return sheet;
        }

    }
}

【讨论】:

    【解决方案2】:

    由于 BulkSmsModel 类中的属性名称与电子表格中的列名称不直接相关,因此您需要将属性名称映射到列名称。

    假设 messages 是 ExcelQueryFactory 对象,这就是代码。

    var messages = new ExcelQueryFactory("excelFileName");
    messages.AddMapping<BulkSmsModel>(x => x.receipient_name, "Name");
    messages.AddMapping<BulkSmsModel>(x => x.receipient_number, "Number");
    
    var receipients = from n in messages.Worksheet<BulkSmsModel>(sheetName)
                      select n;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 2016-11-22
      • 2023-02-25
      • 1970-01-01
      相关资源
      最近更新 更多