使用EPPlus将excel文件导入数据库

时间:2016-07-07 16:16:16

标签: asp.net excel import epplus

我很难理解应该是一项简单的任务。我现在正在使用EEPlus来帮助我完成这项任务,但是我无法跟踪正在发生的事情。 (根据下面的评论和谷歌搜索的日子)我正在尝试读取excel文件并将其传递给我的EF模型。它在第159行分解,我试图从excel文件中输入值但是仍然是null。但是,当查看第159行的值时,它们都具有正确的信息。我不确定如何跟踪这样的错误。

TruckController.cs

    // POST: Trucks/Import
    [HttpPost]
    public ActionResult Import(FormCollection formCollection)
    {
        if (Request != null)
        {
            HttpPostedFileBase file = Request.Files["file"];


            if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
            {
                file.SaveAs(Server.MapPath("~/" + "test.xlsx"));
                //string fileName = file.FileName;
              //  string fileContentType = file.ContentType;
                byte[] fileBytes = new byte[file.ContentLength];
               // var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
                var MyImport = new List<string>();
               MyImport = ImportDataRecords(new FileInfo(Server.MapPath("~/" ) + "test.xlsx"));
            }
        }
        return View("Import");
    }

    public List<string> ImportDataRecords(FileInfo file)
    {
        var resultMessages = new List<string>();
        var totalImported = 0;
        try
        {
            using (var excelPackage = new ExcelPackage(file))
            {
                string DeliveryColumn,
                    ItemNoColumn,
                    MaterialColumn,
                    MaterialDescriptionColumn,
                    DeliveryQtytoPickColumn,
                    PickedQuantityColumn,
                    SalesUoMColumn,
                    BatchPickedColumn,
                    BinNoColumn,
                    BagWeightColumn,
                    PalletNoColumn,
                    PalletStackingNoColumn,
                    StageNoColumn,
                    SubStopNoColumn,
                    PickStatusColumn,
                    PackStatusColumn,
                    SoldToColumn,
                    SoldToNameColumn,
                    ShipToNameColumn;

                if (!file.Name.EndsWith("xlsx"))
                {
                    resultMessages.Add("File selected is not an Excel file");
                    return resultMessages;
                }

                var worksheet = excelPackage.Workbook.Worksheets[1];
                if (worksheet == null)
                {
                    resultMessages.Add("File was empty");
                    return resultMessages;
                }

                using (var headers = worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column])
                {
                    var expectedHeaders = new[]
                    {
                        "Delivery", "Item No.", "Material", "Material Description", "Delivery Qty to Pick",
                        "Picked Quantity", "Sales UoM", "Batch Picked", "BIN No.", "Bag Weight", "Pallet No.",
                        "Pallet Stacking No", "Stage No", "Sub Stop No", "Pick Status", "Pack Status", "Sold-To",
                        "Sold-To Name", "Ship-To Name"
                    };
                    if (!expectedHeaders.All(e => headers.Any(h => h.Value.Equals(e))))
                    {
                        resultMessages.Add("Some columns are missing from the file");
                        return resultMessages;
                    }

                    DeliveryColumn = headers.First(h => h.Value.Equals("Delivery")).Address[0].ToString();
                    ItemNoColumn = headers.First(h => h.Value.Equals("Item No.")).Address[0].ToString();
                    MaterialColumn = headers.First(h => h.Value.Equals("Material")).Address[0].ToString();
                    MaterialDescriptionColumn = headers.First(h => h.Value.Equals("Material Description")).Address[0].ToString();
                    DeliveryQtytoPickColumn = headers.First(h => h.Value.Equals("Delivery Qty to Pick")).Address[0].ToString();
                    PickedQuantityColumn = headers.First(h => h.Value.Equals("Picked Quantity")).Address[0].ToString();
                    SalesUoMColumn = headers.First(h => h.Value.Equals("Sales UoM")).Address[0].ToString();
                    BatchPickedColumn = headers.First(h => h.Value.Equals("Batch Picked")).Address[0].ToString();
                    BinNoColumn = headers.First(h => h.Value.Equals("BIN No.")).Address[0].ToString();
                    BagWeightColumn = headers.First(h => h.Value.Equals("Bag Weight")).Address[0].ToString();
                    PalletNoColumn = headers.First(h => h.Value.Equals("Pallet No.")).Address[0].ToString();
                    PalletStackingNoColumn = headers.First(h => h.Value.Equals("Pallet Stacking No")).Address[0].ToString();
                    StageNoColumn = headers.First(h => h.Value.Equals("Stage No")).Address[0].ToString();
                    SubStopNoColumn = headers.First(h => h.Value.Equals("Sub Stop No")).Address[0].ToString();
                    PickStatusColumn = headers.First(h => h.Value.Equals("Pick Status")).Address[0].ToString();
                    PackStatusColumn = headers.First(h => h.Value.Equals("Pack Status")).Address[0].ToString();
                    SoldToColumn = headers.First(h => h.Value.Equals("Sold-To")).Address[0].ToString();
                    SoldToNameColumn = headers.First(h => h.Value.Equals("Sold-To Name")).Address[0].ToString();
                    ShipToNameColumn = headers.First(h => h.Value.Equals("Ship-To Name")).Address[0].ToString();

                    using (var context = new EPPlusTruckContext())
                    {

                        var lastRow = worksheet.Dimension.End.Row;
                        for (var row = 2; row <= lastRow; row++)
                        {
-----------Line 159-------------> var truck = new Truck()
                            {
                                Delivery = worksheet.Cells[DeliveryColumn + row].Value.ToString(),
                                ItemNo = worksheet.Cells[ItemNoColumn + row].Value.ToString(),
                                Material = worksheet.Cells[MaterialColumn + row].Value.ToString(),
                                MaterialDescription = worksheet.Cells[MaterialDescriptionColumn + row].Value.ToString(),
                                DeliveryQtyToPick = worksheet.Cells[DeliveryQtytoPickColumn + row].Value.ToString(),
                                PickedQuantity = worksheet.Cells[PickedQuantityColumn + row].Value.ToString(),
                                SalesUoM = worksheet.Cells[SalesUoMColumn + row].Value.ToString(),
                                BatchPicked = worksheet.Cells[BatchPickedColumn + row].Value.ToString(),
                                BinNo = worksheet.Cells[BinNoColumn + row].Value.ToString(),
                                BagWeight = worksheet.Cells[BagWeightColumn + row].Value.ToString(),
                                PalletNo = worksheet.Cells[PalletNoColumn + row].Value.ToString(),
                                PalletStackingNo = worksheet.Cells[PalletStackingNoColumn + row].Value.ToString(),
                                StageNo = worksheet.Cells[StageNoColumn + row].Value.ToString(),
                                SubStopNo = worksheet.Cells[SubStopNoColumn + row].Value.ToString(),
                                PickStatus = worksheet.Cells[PickStatusColumn + row].Value.ToString(),
                                PackStatus = worksheet.Cells[PackStatusColumn + row].Value.ToString(),
                                SoldTo = worksheet.Cells[SoldToColumn + row].Value.ToString(),
                                SoldToName = worksheet.Cells[SoldToNameColumn + row].Value.ToString(),
                                ShipToName = worksheet.Cells[ShipToNameColumn + row].Value.ToString(),
                            };

                                db.Trucks.Add(truck);

                            try
                            {
                                db.SaveChanges();
                                totalImported++;
                            }
                            catch (Exception ex)
                            {

                                resultMessages.Add(string.Format("Record on line#{0} failed: {1}\n", row, ex.Message));
                            }
                        }

                    }

                }
                resultMessages.Insert(0, string.Format("{0} records successfully imported.\n", totalImported));
                return resultMessages;
            }

        }
        catch (IOException ex)
        {
            resultMessages.Add("File still open. Please close Excel file before importing.");
            return resultMessages;
        }
    }

1 个答案:

答案 0 :(得分:0)

一个简单的例子:
Reff:http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/

public bool readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        string queryString = "INSERT INTO tableName VALUES";        //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
        string eachVal = "";
        bool status;
        for (int row = 1; row <= rowCount; row++)
        {
            queryString += "(";
            for (int col = 1; col <= colCount; col++)
            {
                eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
                queryString += "'" + eachVal + "',";
            }
            queryString = queryString.Remove(queryString.Length - 1, 1);    //removing last comma (,) from the string
            if (row % 1000 == 0)        //On every 1000 query will execute, as maximum of 1000 will be executed at a time. 
            {
                queryString += ")";
                status = this.runQuery(queryString);    //executing query
                if (status == false)
                    return status;
                queryString = "INSERT INTO tableName VALUES";
            }
            else
            {
                queryString += "),";
            }
        }
        queryString = queryString.Remove(queryString.Length - 1, 1);    //removing last comma (,) from the string
        status = this.runQuery(queryString);    //executing query
        return status;
    }
}