使用asp.net mvc将数据从csv文件插入dabase

时间:2016-04-15 11:19:13

标签: asp.net-mvc

我想从csv文件中将数据插入表ItemPromo: 但是当我测试代码时,数据没有插入,当我调试时,我发现StreamReader sr = new StreamReader(fileName); return null
这是我的Controller ItemPromoesController:

public class ItemPromoesController : Controller
{
    private CitroContext db = new CitroContext();

    // Cette fonction permet de mettre les donnes de fichier dans un table 
    private static DataTable ProcessCSV(string fileName)
    {
        //Set up our variables
        string Feedback = string.Empty;
        string line = string.Empty;
        string[] strArray;
        DataTable dt = new DataTable();
        DataRow row;
        // work out where we should split on comma, but not in a sentence
        Regex r = new Regex(";(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

        //Set the filename in to our stream
        StreamReader sr = new StreamReader(fileName);

        //Read the first line and split the string at , with our regular expression in to an array
        line = sr.ReadLine();
        strArray = r.Split(line);

        //For each item in the new split array, dynamically builds our Data columns. Save us having to worry about it.
        Array.ForEach(strArray, s => dt.Columns.Add(new DataColumn()));

        //Read each line in the CVS file until it’s empty
        while ((line = sr.ReadLine()) != null)
        {
            row = dt.NewRow();

            //add our current value to our data row
            row.ItemArray = r.Split(line);
            dt.Rows.Add(row);
        }

        //Tidy Streameader up
        sr.Dispose();

        //return a the new DataTable
        return dt;

    }

    //cette fonction permet de copier les données de table dans la table ItemPromo : 
    private static String ProcessBulkCopy(DataTable dt)
    {
        string Feedback = string.Empty;
        string connString = ConfigurationManager.ConnectionStrings["CitroContext"].ConnectionString;

        //make our connection and dispose at the end
        using (SqlConnection conn = new SqlConnection(connString))
        {
            //make our command and dispose at the end
            using (var copy = new SqlBulkCopy(conn))
            {
                //Open our connection
                conn.Open();

                ///Set target table and tell the number of rows
                copy.DestinationTableName = "ItemPromo";
                copy.BatchSize = dt.Rows.Count;
                try
                {
                    //Send it to the server
                    copy.WriteToServer(dt);
                    Feedback = "Upload complete";
                }
                catch (Exception ex)
                {
                    Feedback = ex.Message;
                }
            }
        }

        return Feedback;
    }

    // GET: ItemPromoes
    public ActionResult Index()
    {
        return View(db.ItemPromoes.ToList());
    }

    // POST: ItemPromoes
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase fichier)
    {
        // Set up DataTable place holder
        DataTable dt = new DataTable();
        //check we have a file
        if (fichier.ContentLength > 0)
        {
            string fileName = Path.GetFileName(fichier.FileName);
            string path = Path.Combine(Server.MapPath("~/Files/"), fileName);
            //Try and upload
            try
            { 
                 fichier.SaveAs(path);
                //Process the CSV file and capture the results to our DataTable place holder
                dt = ProcessCSV(path);

                //Process the DataTable and capture the results to our SQL Bulk copy
                ViewData["Feedback"] = ProcessBulkCopy(dt);
            }
            catch (Exception ex)
            {
                //Catch errors
                ViewData["Feedback"] = ex.Message;
            }
        }
        else
        {
            //Catch errors
            ViewData["Feedback"] = "Please select a file";
        }
        //Tidy up
        dt.Dispose();
        return View(db.ItemPromoes.ToList()}

这是我的观点:

 @using (Html.BeginForm("Index", "ItemPromoes", FormMethod.Post, new { @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
            {
                @Html.AntiForgeryToken()

                <div class="form-horizontal">

                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group">
                        <div class="col-md-6 col-sm-6 col-xs-12">
                            <div class="editor-field">
                                <div class="col-md-6 col-sm-6 col-xs-12">
                                    <input id="DocCSV" title="Importer un fichier ... "
                                           type="file" name="fichier" />
                                </div>
                                </div>
                        </div>
                    </div>

                    <div class="ln_solid"></div>
                    <div class="form-group">
                        <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
                            <input type="submit" class="btn btn-success" value="Valider" name="submit" />
                            <input type="reset" class="btn btn-primary" value="Annuler" name="submit" />
                        </div>
                    </div>
                </div>
            }


            <table id="example" class="table table-striped responsive-utilities jambo_table">
                <thead>
                    <tr class="headings">
                        <th>
                            @Html.DisplayNameFor(model => model.NumArticle)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.Remise)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.DateDebut)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.DateFin)
                        </th>
                    </tr>
                </thead>
                @foreach (var item in Model)
                {
                    <tbody>
                        <tr class="even pointer">
                            <td>
                                @Html.DisplayFor(modelItem => item.NumArticle)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.Remise)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.DateDebut)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.DateFin)
                            </td>
                        </tr>
                    </tbody>
                }

            </table>

这是我的课程ItemPromo:

[Table("ItemPromo")]
public partial class ItemPromo
{
    [Key]
    [StringLength(50)]
    public string NumArticle { get; set; }

    public decimal Remise { get; set; }

    [Column(TypeName = "date")]
    public DateTime? DateDebut { get; set; }

    [Column(TypeName = "date")]
    public DateTime? DateFin { get; set; }
}

有人可以帮助找到错误 感谢

0 个答案:

没有答案