如何使用mvc razor将csv文件上传到数据库? [英] how to upload csv file to database using mvc razor?

查看:155
本文介绍了如何使用mvc razor将csv文件上传到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照这篇文章将csv文件上传到sql server数据库,但本教程在aspx mvc2 ..所以我无法使它工作..它也给了我几个例外。



http://arranmaclean.wordpress.com/2010/07/20/net-mvc-upload-a-csv-file-to-database-with-bulk-upload/ [ ^ ]



HomeController代码





 [HttpPost] 
public ActionResult Index(HttpPostedFileBase FileUpload)
{

DataTable dt = new DataTable();


if (FileUpload.C​​ontentLength > 0
{

string fileName = Path.GetFileName(FileUpload.FileName );
string path = Path.Combine(Server.MapPath( 〜/ App_Data / uploads),fileName);


try
{
FileUpload.SaveAs(path);

dt = ProcessCSV(路径);


ViewData [ 反馈] = ProcessBulkCopy(dt );
}
catch (例外情况)
{

ViewData [ Feedback] = ex.Message;
}
}
其他
{

ViewData [ 反馈] = 请选择一个文件;
}


dt.Dispose();

return 查看( 索引,ViewData [ 反馈]);
}

私有 静态 DataTable ProcessCSV( string fileName)
{

string Feedback = .Empty;
string line = string .Empty;
string [] strArray;
DataTable dt = new DataTable();
DataRow行;


正则表达式r = 正则表达式( ,(=(:???![^ \ ] * \[^ \ ] * \)*([^ \ ] * \) ));


StreamReader sr = new StreamReader(fileName);


line = sr.ReadLine();
strArray = r.Split(line);


Array.ForEach(strArray,s = > dt.Columns.Add( new DataColumn()));



while ((line = sr.ReadLine())!= null
{
row = dt.NewRow();


row.ItemArray = r.Split(line);
dt.Rows.Add(row);
}


sr.Dispose();


return dt;


}


private static 字符串 ProcessBulkCopy(DataTable dt)
{
string 反馈= string .Empty;
string connString = ConfigurationManager.ConnectionStrings [ MyConnection的]的ConnectionString。


使用(SqlConnection conn = new SqlConnection(connString) )
{

使用 var copy = new SqlBulkCopy(conn))
{


conn.Open();


copy.DestinationTableName = BulkImportDetails;
copy.BatchSize = dt.Rows.Count;
尝试
{

copy.WriteToServer(dt);
反馈= 上传完成;
}
catch (例外情况)
{
Feedback = ex.Message;
}
}
}

返回反馈;
}







指数Razor查看



 @ {
ViewBag.Title =Index;
}

< h2 > 索引< / h2 >

@ {
ViewBag.Title =主页;
}
< h2 > CSV批量上传< / h2 >
@ {using(Html.BeginForm(,,FormMethod.Post,new {enctype =multipart / form-data}))
{
< 输入 类型 = file name = FileUpload / >
< 输入 type = submit 名称 = < span class =code-keyword>提交 id = 提交 = 上传 / >
}
}

< p > @ {Html .Encode(ViewData [Feedback]);} < / p >





目前,我通过反馈获得无文件选择异常。

解决方案





使用以下链接



http://stackoverflow.com/questions/21556551/bulk-uploading- of-images-to-server-using-csv-mvc3-and-razor-view [ ^ ]

http://stackoverflow.com/questions/13963253/uploading-csv-file-using-c-sharp -asp-net-mvc [ ^ ]

http://arranmaclean.wordpress.com/2010/07/20/ net-mvc-upload-a-csv-file-to-database-with-bulk-upload / [ ^ ]

http://www.dotnet-tricks.com/Tutorial /mvc/WKNQ120113-How-to-upload-a-file-in-MVC4.html [ ^ ]


http://arranmaclean.wordpress.com / 2010/07/20 / net-mvc-upload-a-csv-file-to-database-with-bulk-upload / [^] [ ^ ]



这篇文章太棒了。我刚刚将aspx转换为chtml。代码..你可以在我的问题中看到代码。 :)傻我。我忘了更新数据库,现在一切正常。 :)

hi, there I am following this article to upload csv file into sql server database but this tutorial in aspx mvc2.. so I am not able to make it work.. also it is giving me several exceptions.

http://arranmaclean.wordpress.com/2010/07/20/net-mvc-upload-a-csv-file-to-database-with-bulk-upload/[^]

HomeController Code


[HttpPost]
       public ActionResult Index(HttpPostedFileBase FileUpload)
       {

           DataTable dt = new DataTable();


           if (FileUpload.ContentLength > 0)
           {

               string fileName = Path.GetFileName(FileUpload.FileName);
               string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);


               try
               {
                   FileUpload.SaveAs(path);

                   dt = ProcessCSV(path);


                   ViewData["Feedback"] = ProcessBulkCopy(dt);
               }
               catch (Exception ex)
               {

                   ViewData["Feedback"] = ex.Message;
               }
           }
           else
           {

               ViewData["Feedback"] = "Please select a file";
           }


           dt.Dispose();

           return View("Index", ViewData["Feedback"]);
       }

       private static DataTable ProcessCSV(string fileName)
       {

           string Feedback = string.Empty;
           string line = string.Empty;
           string[] strArray;
           DataTable dt = new DataTable();
           DataRow row;


           Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");


           StreamReader sr = new StreamReader(fileName);


           line = sr.ReadLine();
           strArray = r.Split(line);


           Array.ForEach(strArray, s => dt.Columns.Add(new DataColumn()));



           while ((line = sr.ReadLine()) != null)
           {
               row = dt.NewRow();


               row.ItemArray = r.Split(line);
               dt.Rows.Add(row);
           }


           sr.Dispose();


           return dt;


       }


       private static String ProcessBulkCopy(DataTable dt)
       {
           string Feedback = string.Empty;
           string connString = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;


           using (SqlConnection conn = new SqlConnection(connString))
           {

               using (var copy = new SqlBulkCopy(conn))
               {


                   conn.Open();


                   copy.DestinationTableName = "BulkImportDetails";
                   copy.BatchSize = dt.Rows.Count;
                   try
                   {

                       copy.WriteToServer(dt);
                       Feedback = "Upload complete";
                   }
                   catch (Exception ex)
                   {
                       Feedback = ex.Message;
                   }
               }
           }

           return Feedback;
       }




Index Razor View

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@{
    ViewBag.Title = "Home Page";
}
<h2>CSV Bulk Upload</h2>
@{ using (Html.BeginForm("", "", FormMethod.Post, new { enctype = "multipart/form-data" }))
 {
    <input type="file" name="FileUpload" />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
 }
}

<p>@{ Html.Encode(ViewData["Feedback"]);} </p>



Currently, I am getting "no file selected exception" via Feedback.

解决方案

Hi,

Use below links

http://stackoverflow.com/questions/21556551/bulk-uploading-of-images-to-server-using-csv-mvc3-and-razor-view[^]
http://stackoverflow.com/questions/13963253/uploading-csv-file-using-c-sharp-asp-net-mvc[^]
http://arranmaclean.wordpress.com/2010/07/20/net-mvc-upload-a-csv-file-to-database-with-bulk-upload/[^]
http://www.dotnet-tricks.com/Tutorial/mvc/WKNQ120113-How-to-upload-a-file-in-MVC4.html[^]


http://arranmaclean.wordpress.com/2010/07/20/net-mvc-upload-a-csv-file-to-database-with-bulk-upload/[^][^]

This article is awesome . I just converted aspx to chtml. codes.. you can see the code in my question. :) silly me. I forgot to update the database, now everything is working fine. :)


这篇关于如何使用mvc razor将csv文件上传到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆