簡體   English   中英

使用LinqToCsv將CSV文件寫入Sql數據庫-.NET MVC 4-實體框架

[英]Writing CSV files into Sql database using LinqToCsv - .NET MVC 4 - Entity Framework

我正在嘗試創建一個應用程序,用戶可以在其中將.CSV文件上傳到我創建的SQL數據庫中。 當涉及到從視圖中實際獲取文件路徑並將其寫入數據庫時​​,我有些困惑。

首先,這是我正在研究的模型:

    public class OutstandingCreditCsv
{
    [CsvColumn(FieldIndex = 1, CanBeNull = false)]
    public string PoNumber { get; set; }
    [CsvColumn(FieldIndex = 2, OutputFormat = "dd MMM HH:mm:ss")]
    public DateTime CreditInvoiceDate { get; set; }
    [CsvColumn(FieldIndex = 3)]
    public string CreditInvoiceNumber { get; set; }
    [CsvColumn(FieldIndex = 4, CanBeNull = false, OutputFormat = "C")]
    public decimal CreditInvoiceAmount { get; set; }
}

到目前為止,這是控制器代碼:

        public ActionResult Index()
    {
        CsvFileDescription inputFileDescription = new CsvFileDescription
        {
            SeparatorChar = ',',
            FirstLineHasColumnNames = true
        };

        var context = new CsvContext();

        IEnumerable<OutstandingCreditCsv> csvList =
        context.Read<OutstandingCreditCsv>("C:/Users/BlahBlah/Desktop/CsvUploadTestFile.csv", inputFileDescription);

        foreach (OutstandingCreditCsv line in csvList)
        {

        }

        return View();
    }

我需要在兩個方面提供一些指導。 我不確定如何將文件從視圖傳遞到控制器,可以說我的視圖很簡單:

<form action="" method="POST" enctype="multipart/form-data">
<table style="margin-top: 150px;">
    <tr>
        <td>
            <label for="file">Filename:</label>
        </td>
        <td>
            <input type="file" name="file" id="file"/>
        </td>
        <td><input type="submit" value="Upload"/></td>
    </tr>
</table>
</form>

我也不確定如何將csv數據實際循環到數據庫中。 您可以看到控制器中的foreach循環為空。 任何幫助,將不勝感激。 謝謝!

我正在編輯帖子,以回答我遺漏的部分問題。 您在這里所做的就是將csv文件上傳到一個臨時位置,將其讀入一個對象,然后,如果需要,您可以從該臨時位置中刪除csv文件(未顯示)。

[HttpPost]
public JsonResult UploadValidationTable(HttpPostedFileBase csvFile)
{
    CsvFileDescription inputFileDescription = new CsvFileDescription
    {
         SeparatorChar = ',',
         FirstLineHasColumnNames = true
    };

    var cc = new CsvContext();
    string filePath = uploadFile(csvFile.InputStream);
    var model = cc.Read<OutstandingCreditCsv>(filePath, inputFileDescription);

    //if your csv has several rows convert it to a list of your model
    //var model = cc.Read<List<OutstandingCreditCsv>>(filePath, inputFileDescription);
   //then you can loop through and do the same as below
   /*foreach(var row in model)
   {
        var invoice = row.CreditInvoiceNumber;
   }*/

    try
    {
        //do what you need here, like save items to database
        var invoice = model.CreditInvoiceNumber;

        var invoiceTable = yourContext.yourTable
            .FirstOrDefault(x => x.yourTableID == passedInId);

       invoiceTable.CreditInvoiceNumber = model.CreditInvoiceNumber;
       yourContext.SaveChanges();
    }
    catch(LINQtoCSVException ex)
    {

    }

    return Json(model, "text/json");
}

private string uploadFile(Stream serverFileStream)
{
    string directory = "~/Content/CSVUploads";

    bool directoryExists = System.IO.Directory.Exists(Server.MapPath(directory));

    if (!directoryExists)
    {
        System.IO.Directory.CreateDirectory(Server.MapPath(directory));
    }

    string targetFolder = Server.MapPath(directory);
    string filename = Path.Combine(targetFolder, Guid.NewGuid().ToString() + ".csv");

    try
    {
        int length = 256; //todo: replace with actual length
        int bytesRead = 0;
        Byte[] buffer = new Byte[length];

        // write the required bytes
        using (FileStream fs = new FileStream(filename, FileMode.Create))
        {
            do
            {
                bytesRead = serverFileStream.Read(buffer, 0, length);
                fs.Write(buffer, 0, bytesRead);
            }
            while (bytesRead == length);
        }

        serverFileStream.Dispose();
        return filename;
    }
    catch (Exception ex)
    {
        return string.Empty;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM