MVC4 导入execl和下载模板

上传预览

var IsIllegal = false;
        function SelectFile(obj) {
            document.getElementById(‘textfield‘).value = obj.value;
            IsIllegal = false;
        }

<input type=‘text‘ disabled="disabled" name=‘textfield‘ id=‘textfield‘ class=‘txt‘ />
<input type=‘button‘ class=‘btn‘ value=‘浏览‘ />

<input type="file" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" name="excel" class="file" id="excel" onchange="SelectFile(this)" /> 打资源管理器添加execl文件

$("上传按钮ID").click(function () {
            if ($(‘放置execl文件的文本框ID‘).val().length == 0) {
                alert(‘请选择要上传的文件~!‘);
                return false;
            }
         
            $("表单ID").ajaxSubmit(options);
        });

var options = {
            url: ‘Controller/Action‘,
            success: function (后台回传数据) {
              需求;
        };

#region

public ActionResult ProExcel(HttpPostedFileBase excel)//保存到程序缓存
        {
            if (excel == null)//判断有没有选择文件
            {
                return Json(new { InfoCode = "1000", Msg = "请添加 excel文件~!" });
            }
            List<ProMacCreatExcelModel> models = new List<ProMacCreatExcelModel>();//定义一个有三列的类
            try
            {
                using (excel.InputStream)
                {
                    string fileName = excel.FileName;
                    string ext = fileName.Substring(fileName.LastIndexOf(‘.‘) + 1);
                    string s = Path.GetExtension(fileName);
                    if (s != ".xls" && s != ".xlsx")//判断是不是execl格式的文件
                    {
                        return Json(new { InfoCode = "1000", Msg = "请添加 excel文件~!" });
                    }
                    IWorkbook workbook;//一个execl文件
                    if (!(ext.Equals("xls") || ext.Equals("xlsx")))//判断是不是execl格式的文件
                    {
                        return Json(new { InfoCode = "1000", Msg = "请添加 excel文件~!" });
                    }
                    if (ext.Equals("xls"))
                        workbook = new HSSFWorkbook(excel.InputStream);//把execl文件读到web里
                    else
                        workbook = new XSSFWorkbook(excel.InputStream);

ISheet sheet = workbook.GetSheetAt(0);//取第一个表

DataTable table = new DataTable();

IRow headerRow = sheet.GetRow(0);//第一行为标题行
                    int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                    int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
                    //handling header.
                    for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                    {
                        DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                        table.Columns.Add(column);
                    }

for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        DataRow dataRow = table.NewRow();

if (row != null)
                        {
                            for (int j = row.FirstCellNum; j < cellCount; j++)
                            {
                                if (row.GetCell(j) != null)
                                {
                                    dataRow[j] = row.GetCell(j).GetCellValue();
                                }

}
                        }

table.Rows.Add(dataRow);
                    }
                    foreach (DataRow row in table.Rows)
                    {
                        ProMacCreatExcelModel t = new ProMacCreatExcelModel();
                        t.cell1 = row[0].ObjToString();
                        t.cell2 = row[1].ObjToString();
                        if (table.Columns.Count == 3)
                            t.cell3 = row[2].ObjToString();
                        models.Add(t);
                    }
                    return Json(new { InfoCode = "0000", data = models });
                }
            }
            catch (Exception ex)
            {
                CustomerFilterAttribute.ErrorQueue.Enqueue(ex);
                return Json(new { InfoCode = "4000", data = models });
            }
        }

#endregion

#region Model层定义的类

public class ProMacCreatExcelModel
    {
        public string cell1 { get; set; }
        public string cell2 { get; set; }
        public string cell3 { get; set; }
    }

#endregion

public ActionResult ProMultityInport(Dto_ProdMacProMI PMPI)//保存到数据库
        {
            using (PMPI.excel.InputStream)
            {
                try
                {
                    string fileName = PMPI.excel.FileName;
                    string ext = fileName.Substring(fileName.LastIndexOf(‘.‘) + 1);
                    IWorkbook workbook;
                    if (ext.Equals("xls"))
                        workbook = new HSSFWorkbook(PMPI.excel.InputStream);
                    else
                        workbook = new XSSFWorkbook(PMPI.excel.InputStream);

ISheet sheet = workbook.GetSheetAt(0);//取第一个表

DataTable table = new DataTable();

IRow headerRow = sheet.GetRow(0);//第一行为标题行
                    int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                    int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
                    List<prodmaccreat> models = new List<prodmaccreat>();
                    //handling header.
                    for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                    {
                        DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                        table.Columns.Add(column);
                    }

for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        DataRow dataRow = table.NewRow();

if (row != null)
                        {
                            for (int j = row.FirstCellNum; j < cellCount; j++)
                            {
                                if (row.GetCell(j) != null)
                                {
                                    dataRow[j] = row.GetCell(j).GetCellValue();
                                }

}
                        }

table.Rows.Add(dataRow);
                    }
                    foreach (DataRow row in table.Rows)
                    {
                        models.Add(new prodmaccreat()
                        {
                            cid = row[0].ObjToString(),
                            macno = row[1].ObjToString(),
                            ptserial = string.IsNullOrEmpty(PMPI.ptserial) ? null : PMPI.ptserial,
                            uiversion = string.IsNullOrEmpty(PMPI.uiversion) ? null : PMPI.uiversion,
                            mscserial = string.IsNullOrEmpty(PMPI.mscserial) ? null : PMPI.mscserial,
                            utid = int.Parse(PMPI.utid),
                            officialversion = PMPI.officialversion,
                            developmentversion = PMPI.developmentversion,
                            suhardver = PMPI.suhardver,
                            susoftver = PMPI.susoftver,
                            state = "0",
                            importdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        });
                    }
                    List<string> cids2 = (from o in models join p in prodmaccreatbll.GetList(o => true).ToList() on o.cid equals p.cid select o.cid).ToList();
                    if (cids2.Count != 0)
                    {
                        string s = "";
                        cids2.ForEach(c =>
                        {
                            s = s + c + ",";
                        });
                        return Json(new { InfoCode = "4000", Msg = "盒子ID" + s + "重复!" });
                    }
                    prodmaccreatbll.AddModels(models);
                    var cids = (from o in models select o.cid).ToArray();
                    MongoWSModel prodmaccreatdataModel = new MongoWSModel(ActionOption.add)
                    {
                        TableName = "prodmaccreat",
                        KeyName = "cid",
                        KeyValue = cids
                    };
                    for (int i = 1; 1 <= 3; i++)
                    {
                        bool res = client.PushData(JsonConvert.SerializeObject(prodmaccreatdataModel));
                        if (res)
                            break;
                    }
                    List<ProMacCreatExcelModel> prodmaccreatexcekmodel = new List<ProMacCreatExcelModel>();
                    foreach (DataRow row in table.Rows)
                    {
                        ProMacCreatExcelModel t = new ProMacCreatExcelModel();
                        t.cell1 = row[0].ObjToString();
                        t.cell2 = row[1].ObjToString();
                        if (table.Columns.Count == 3)
                            t.cell3 = row[2].ObjToString();
                        prodmaccreatexcekmodel.Add(t);
                    }
                    WriteLog("000010002005", "导入用户", true);
                    return Json(new { InfoCode = "0000", data = prodmaccreatexcekmodel });
                }
                catch (Exception ex)
                {
                    WriteLog("000010002005", "导入用户", false);
                    CustomerFilterAttribute.ErrorQueue.Enqueue(ex);
                    return Json(new { InfoCode = "4000", Msg = "系统异常~!" });
                }
            }
        }

<a style="font-size:12px;color:blue;" href="~/Content/themes/DownLoadFiles/批量导入用户模板.xlsx">下载导入模板</a>

时间: 2024-10-09 04:27:58

MVC4 导入execl和下载模板的相关文章

vue的下载模板,批量导入

1.下载模板是 然后下面都是方法的操作 2.批量导入是

ASP.NET之Excel下载模板、导入、导出操作

1.下载模板功能 前提是服务器某文件夹中有这个文件.代码如下 1 protected void btnDownload_Click(object sender, EventArgs e) 2 { 3 var path = Server.MapPath(("upfiles\\") + "test.xlt"); //upfiles-文件夹 test.xlt-文件 4 var name = "test.xlt"; 5 6 try 7 { 8 var f

下载模板、Excel导入、导出

下载模板 /// <summary> /// 下载模板 /// </summary> /// <returns></returns> public ActionResult DownTemplate() { string path = Server.MapPath("/Template/TeacherTpl.xlsx"); return File(new FileStream(path, FileMode.Open), "app

SqlServer2008 脚本导入Execl数据

使用SQL脚本导入Execl数据,是使用SQL的链接服务器的访问接口来完成的. 1.所以首先,需要数据库中有对应的Execl访问接口,使用的是SQlServer2008R2+Office2013,所以安装使用的是ACE2010的驱动 下载地址:  http://www.microsoft.com/zh-cn/download/details.aspx?id=13255 安装之后在数据会有对应的访问接口 2.开启Ad Hoc Distributed Queries --开启Ad Hoc Distr

springboot 下载模板文件 加载classpath文件路径

项目需要下载导入模板,springboot使用如下下载方式可解决问题: /** * 导入模板下载 * @param req * @param resp * @param context * @return */ @RequestMapping(value = "wSku/downLoadFile", method = {RequestMethod.POST, RequestMethod.GET}) public @ResponseBody void downLoadFile(HttpS

Web页中table导出到execl(带模板)

1.将excel另存为html,将其复制到aspx文件中 2.输出格式为excel InitData(); Response.Clear(); Response.Buffer = true; Response.Charset = "GB2312"; Response.AddHeader("Content-Disposition", "attachment; filename=" + new AutoNumber().GetNumberByTime

(模板)网页游戏用的“内容区”的“游戏下载”模板

网页游戏用的"内容区"的下载模板 <style> .article-main{ width:939px; } /*下载中心*/ .big_pub_right { width:960px; } .faq p { line-height:25px; } .pub_title { background:#353b42; height:84px; color:#969db0; line-height:84px; padding:0px 20px; } .pub_title a {

悟空CRM框架下载模板

1.你可以把你要下载的模板放在这个项目的Public/excelmodel目录下,然后你就可以在页面中编写代码 你可以在下载按钮这里编写:onclick="window.location.href='__ROOT__/Public/excelmodel/yxpyks.xls'" yxpyks.xls 这个是你要下载的模板. 这样子就不用编写下载模板的代码了.

java poi 从服务器下载模板写入数据再导出

最近写了一个,Excel 的 写入和导出.   需求是这样的.   在新建合同的时候,会有导出合同的数据,    导出的模板是固定的,,需要在模板里面写入合同的信息. first   :  下载模板   > 写入数据 > 输出 下载模板  : StringBuilder path = new StringBuilder(""); path.append(request.getSession().getServletContext().getRealPath("&q