mvc 导入excel表格

<script>
    $(function () {
        $("#Attachment").change(function () {
            var att = $("#Attachment").val();
            $("#hid-Attachment").val(att);
        });
    })
</script>
@using (Html.BeginForm("ImportExcel", "ProductOrder", FormMethod.Post, new { id = "ff", enctype = "multipart/form-data" }))
{
    <div class="easyui-panel" title="受理工单" style="width: auto;">
        <div style="padding: 10px 0 10px 400px">
            <table style="text-align: center;">
                <tr>
                    <td>上传附件:</td>
                    <td colspan="3">
                        <input type="file" name="Attachment" id="Attachment" />
                        <input type="hidden" name="hid-Attachment" id="hid-Attachment" />
                    </td>
                </tr>
            </table>
        </div>
        <div style="text-align: center; padding: 5px 220px 10px 250px">
            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="window.history.go(-1)">返回</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()" id="submit">按指定方式处理</a>
            <input type="submit" value="提交" />
        </div>
    </div>

  public ActionResult ImportExcel(HttpPostedFileBase Attachment)
        {
            if (!string.IsNullOrEmpty(Request["hid-Attachment"]))
            {
                string path = this.Server.MapPath(@"../Uploads");
                string fileName = Path.GetFileName(Attachment.FileName);

                uploadInfo.ContentLength = Attachment.ContentLength;
                uploadInfo.FileName = fileName;
                uploadInfo.UploadedLength = 0;

                uploadInfo.IsReady = true;

                int bufferSize = 1;
                byte[] buffer = new byte[bufferSize];

                using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))
                {
                    while (uploadInfo.UploadedLength < uploadInfo.ContentLength)
                    {
                        int bytes = Attachment.InputStream.Read(buffer, 0, bufferSize);
                        fs.Write(buffer, 0, bytes);
                        uploadInfo.UploadedLength += bytes;
                    }
                }
                string file = Path.Combine(path, fileName);
                string result = string.Empty;
                string strConn;
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + file + "; " + "Extended Properties=Excel 8.0;";
                OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
                DataSet myDataSet = new DataSet();
                myCommand.Fill(myDataSet, "ProductOrder");
                System.Data.DataTable tab = myDataSet.Tables["ProductOrder"].DefaultView.ToTable();
                // ...用foreach把tab中数据添加到数据库 省略了如果是多表插入,可以调用存储过程.呵呵
                foreach (DataRow dr in tab.Rows)
                {
                    if (!string.IsNullOrEmpty(dr["商品号"].ToString()))
                    {
                        ProductOrder model = new ProductOrder()
                                      {
                                          CreateTime = dr["日期"].ToString(),
                                          CustomerServices = dr["接待客服"].ToString(),
                                          Customer = dr["顾客姓名"].ToString(),
                                          Address = dr["联系地址"].ToString(),
                                          TEL = dr["联系电话"].ToString(),
                                          ProductName = dr["所购商品"].ToString(),
                                          Quantity = dr["数量"].ToString(),
                                          Price = dr["单价"].ToString(),
                                          Unit = dr["单位"].ToString(),
                                          TotalPrice = dr["总价"].ToString(),
                                          PayoutStatus = dr["支付情况"].ToString(),
                                          OrderId = dr["商品号"].ToString(),
                                          Sim = dr["sim卡号"].ToString(),
                                          SimStatus = dr["sim卡开通情况"].ToString(),
                                          LogisticsId = dr["物流单号"].ToString(),
                                          ReceivingStatus = dr["收货情况"].ToString(),
                                          CollectionStatus = dr["收款情况"].ToString(),
                                      };
                        db.ProductOrders.Add(model);
                        db.SaveChanges();
                    }
                    else
                    {
                          break;
                    }

                }
                #region MyRegion
                //using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy("Data Source=.;Initial Catalog=WorkOrder;Integrated Security=True;MultipleActiveResultSets=True"))
                //{
                //    bcp.ColumnMappings.Add("日期", "CreateTime");
                //    bcp.ColumnMappings.Add("接待客服", "CustomerServices");
                //    bcp.ColumnMappings.Add("顾客姓名", "Customer");
                //    bcp.ColumnMappings.Add("联系地址", "Address");
                //    bcp.ColumnMappings.Add("数量", "Quantity");
                //    bcp.ColumnMappings.Add("所购商品", "ProductName");
                //    bcp.ColumnMappings.Add("联系电话", "TEL");
                //    bcp.ColumnMappings.Add("支付情况", "PayoutStatus");
                //    bcp.ColumnMappings.Add("商品号", "OrderId");
                //    bcp.ColumnMappings.Add("sim卡号", "Sim");
                //    bcp.ColumnMappings.Add("sim卡开通情况", "SimStatus");
                //    bcp.ColumnMappings.Add("物流单号", "LogisticsId");
                //    bcp.ColumnMappings.Add("收货情况", "ReceivingStatus");
                //    bcp.ColumnMappings.Add("收款情况", "CollectionStatus");
                //    bcp.BatchSize = 100;//每次传输的行数
                //    bcp.NotifyAfter = 100;//进度提示的行数
                //    bcp.DestinationTableName = "ProductOrder";//目标表
                //    bcp.WriteToServer(tab);
                //}
                #endregion
                #region MyRegion
                //using (SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=WorkOrder;Integrated Security=True;MultipleActiveResultSets=True"))
                //{
                //    try
                //    {
                //        connection.Open();
                //        //给表名加上前后导符
                //        using (var bulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, null)
                //            {
                //                DestinationTableName = "ProductOrder",
                //                BatchSize = 10000
                //            })
                //        {
                //            //循环所有列,为bulk添加映射
                //            //dataTable.EachColumn(c => bulk.ColumnMappings.Add(c.ColumnName, c.ColumnName), c => !c.AutoIncrement);
                //            foreach (DataColumn dc in tab.Columns)
                //            {
                //                bulk.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);
                //            }
                //            bulk.WriteToServer(tab);
                //            bulk.Close();
                //        }
                //        return View();
                //    }
                //    catch (Exception exp)
                //    {
                //        return View();
                //    }
                //}
                #endregion

                return RedirectToAction("List");
                result = "导入成功!";
                JsonResult json = new JsonResult();
                json.Data = result;
                return json;
            }

            return View();
        }
时间: 2024-08-23 23:58:04

mvc 导入excel表格的相关文章

Asp.NET MVC 导入Excel数据教程 手把手教你系列!!!

先上效果图 1.引言 小弟最近接了个大学生的毕业设计,收了100块钱让做一个ASP.NET MVC导入Excel到数据库的功能,由于以前没做过就到处搜索资料,但是发现网上的资料不是直接贴一大堆乱起八遭的源码,就是需要借用NPOI第三方类库太麻烦了,况且预算才100RMB简直不值得,所以小弟尝试自己动手丰衣足食,所以就有了这篇博客. 先上一张小弟的思路图: (说明:没有安装做流程图的软件!凑合着看吧) 2 进入正题 首先跟着小弟先创建一个默认的MVC项目(相信大家都会创建,这里就不演示了) 第一步

ASP.NET MVC导入excel到数据库

MVC导入excel和webform其实没多大区别,以下为代码: 视图StationImport.cshtml的代码: @{ ViewBag.Title = "StationImport"; Layout = "~/Areas/Admin/Views/Shared/_index.cshtml"; } @using (Html.BeginForm("StationImport", "Station", FormMethod.Po

sqlite expert导入excel表格 (包括使用问题、以及把 一个表的数据插入到另一个表中)

一.sqlite导入excel 1.打开要导入的excel --- 另存为(2007版点击左上角OFFICE图标即可找到) --- 保存类型:CSV类型 (提示什么不兼容什么的,一律点确定.) 2.打开sqlite expert ,选择建好的数据库文件(或者是导入的已存在的db文件,或者是自己新建一个.db数据库文件). 右击文件名---选择最后一个import text file(CSV,TSV) 3.(如果没有建过和这个excel名相同的表)右边Destination选择第一项new tab

phpexcel导入excel表格

html代码 <form action="{:U('Mall/updExcel')}" method="POST" enctype="multipart/form-data"> //提交form表单到Mall控制器下的upExcel方法中 <div style="float:left;width:41%;"> <div style="float:left;"> <i

Java 从数据库中查找信息导入Excel表格中

前端js function Excel (){ //ajax请求 $.ajax({ url : "outPutAboutShopInfo", type : "post", dataType : "json", data:{ "basicShop.shopId" : shopId, "basicShop.shopMemo" : stringType //不方便增加字段所以使用门店的一个"备注&quo

导入Excel表格(二)

1. 提取session中的数据.并进行分页操作,上传excel表格,保存到临时表格. 初始化临时表格,提交表单,判断状态是否为真,若为真,则启用 导入到数据库 的按钮:为false,让查询的url 和数据 为空,写一个方法到控制器查询数据,把数据保存到临时表格.2. 控制器声明一个列表对象,当session的数据不为空时,用来接收保存在session中的数据,然后计算数据的总条数,实例化实体类对象,封装数据,将得到的数据返回到页面. List<studentVo> listStudentVo

使用SqlBulkCopy类实现导入Excel表格

对于C#Execl数据的导入导出大家不感到陌生,这是一个项目中经常回遇到的功能,今天在这里讲的事,使用SqlBulkCopy类实现导入Excel大批量的数据导入. /// <summary> /// 数据库对应表 /// </summary> /// <returns></returns> private static DataTable GetDeliveryOrderTable() { DataTable dt = new DataTable(); dt

PL/SQL 导入excel表格到oracle数据表

通过使用PL/SQL 批量查询取数时,将excel中的每一列数据复制黏贴进新建的中间表,黏贴时会有贴歪的情况,也就是某些列会从第二第三行开始插入整列,导致数据乱掉,然后好像又不支持批量删除整列数据,所以一次性导入整张excel表是最佳方法啦. 第一步: 将excel中要插入oracle的数据全部选中:(必须选中,不然导不进数据库) 第二步: 然后另存为:文本文件(制表符分隔)(*.txt) 第三步: 然后进入PL/SQL 选择工具->文本导入器 第四步: 进行文件的选择: 第五步: 选择文件后就

Asp.Net 导入Excel表格

前台页面: <div align="center" style="background-color:Beige"> <table style="width: 576px; border-collapse: separate; text-align: center"> <tr><td>Excel导入SQL数据库</td></tr> <tr> <td style