简体   繁体   English

使用LinqToCsv将CSV文件写入Sql数据库-.NET MVC 4-实体框架

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

I am trying to create an application in which a user can upload .CSV files into an SQL database that I have created. 我正在尝试创建一个应用程序,用户可以在其中将.CSV文件上传到我创建的SQL数据库中。 I have become a little confused when it comes to actually getting the file path from the view and writing it into the database. 当涉及到从视图中实际获取文件路径并将其写入数据库时​​,我有些困惑。

First off, here is the model that I'm working off: 首先,这是我正在研究的模型:

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

And here is the controller code so far: 到目前为止,这是控制器代码:

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

There are two areas where I need a little guidance. 我需要在两个方面提供一些指导。 I'm not sure how to pass the file from the view to the controller, lets say my view is something simple like this: 我不确定如何将文件从视图传递到控制器,可以说我的视图很简单:

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

I'm also unsure how I would actually loop the csv data into my database. 我也不确定如何将csv数据实际循环到数据库中。 You can see the foreach loop in my controller is empty. 您可以看到控制器中的foreach循环为空。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks! 谢谢!

I am editing my post to answer the part of the question I missed. 我正在编辑帖子,以回答我遗漏的部分问题。 What you are doing here is uploading the csv file to a temporary location, reading it into an object then if you want you can delete the csv file out of the temporary location (not shown). 您在这里所做的就是将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.

相关问题 使用ASP.NET MVC中的Entity Framework将图片上传到SQL服务器数据库 - Upload picture to SQL Server database using Entity Framework in ASP.NET MVC 从MVC .net应用程序使用Entity Framework连接到SQL数据库时出错 - Error connecting to SQL database with Entity Framework from MVC .net application 使用.Net MVC3和Entity Framework将文件存储在SQL Server数据库中 - Store file in SQL Server database using .Net MVC3 with Entity Framework 实体框架/MVC:将集合写入数据库 - Entity Framework / MVC: Writing a collection to the database 使用ASP.NET MVC中的Entity Framework将多张图片上传到SQL服务器数据库 - Upload multiple pictures to SQL Server database using Entity Framework in ASP.NET MVC 使用LinqtoCSV DLL编写.CSV文件 - Writing a .CSV file usingt the LinqtoCSV DLL 实体框架未写入数据库 - Entity Framework not writing to Database 实体框架7与.Net 5 MVC 6中的现有数据库 - Entity Framework 7 With Existing Database in .Net 5 MVC 6 C#如何使用ASP.NET MVC中的实体框架将父数据和子数据插入/更新到sql数据库 - C# How to insert/update the parent and child data to the sql database using entity framework in asp.net mvc 如何使用ASP.NET MVC中的实体框架在SQL Server中保存业务模型实体 - How to save a business model entity in SQL Server using Entity Framework in ASP.NET MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM