日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

mvc手把手教你写excel导入

發布時間:2023/11/27 生活经验 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mvc手把手教你写excel导入 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

實習狗的每天新知識日常

準備工作:

1.在項目中添加對NPOI的引用,NPOI下載地址:http://npoi.codeplex.com/releases/view/38113

2.NPOI學習系列教程推薦:http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html

NPOI下載,里面有五個dll,需要引用到你的項目,我這邊用的mvc4+三層的方式架構的項目

我用的工具是(vs2012+sql2014)

?

準備工作做完,我們開始進入主題

1.前端頁面,代碼:

<div class="filebtn"> @using (Html.BeginForm("importexcel", "foot", FormMethod.Post, new { enctype = "multipart/form-data" })){<samp>請選擇要上傳的Excel文件:</samp><span  id="txt_Path"></span><strong>選擇文件<input name="file" type="file" id="file" /></strong>@*@Html.AntiForgeryToken()  //防止跨站請求偽造(CSRF:Cross-site request forgery)攻擊*@<input type="submit" id="ButtonUpload" value="提交"   class="offer"/> }</div>
excel

2.接下來就是控制器

public class footController : Controller{//// GET: /foot/private static readonly String Folder = "/files";public ActionResult excel(){return View();}/// 導入excel文檔public ActionResult importexcel(){//1.接收客戶端傳過來的數據HttpPostedFileBase file = Request.Files["file"];if (file == null || file.ContentLength <= 0){return Json("請選擇要上傳的Excel文件", JsonRequestBehavior.AllowGet);}//string filepath =  Server.MapPath(Folder);//if (!Directory.Exists(filepath))//{//    Directory.CreateDirectory(filepath);//}//var fileName = Path.Combine(filepath, Path.GetFileName(file.FileName));// file.SaveAs(fileName);//獲取一個streamfile對象,該對象指向一個上傳文件,準備讀取改文件的內容Stream streamfile = file.InputStream;DataTable dt = new DataTable();string FinName = Path.GetExtension(file.FileName);if (FinName != ".xls" && FinName != ".xlsx"){return Json("只能上傳Excel文檔",JsonRequestBehavior.AllowGet);}else{try{if (FinName == ".xls"){//創建一個webbook,對應一個Excel文件(用于xls文件導入類)HSSFWorkbook hssfworkbook = new HSSFWorkbook(streamfile);dt = excelDAL.ImExport(dt, hssfworkbook);}else{XSSFWorkbook hssfworkbook = new XSSFWorkbook(streamfile);dt = excelDAL.ImExport(dt, hssfworkbook);}return Json("",JsonRequestBehavior.AllowGet);}catch(Exception ex){return Json("導入失敗 !"+ex.Message, JsonRequestBehavior.AllowGet);}}}}
footController.cs

3.業務邏輯層[excelDAL]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.Data;
using NPOI.XSSF.UserModel;namespace GJL.Compoent
{public class excelDAL{///<summary>/// #region 兩種不同版本的操作excel/// 擴展名*.xlsx/// </summary>public static DataTable ImExport(DataTable dt, XSSFWorkbook  hssfworkbook){NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);System.Collections.IEnumerator rows = sheet.GetRowEnumerator();for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++){dt.Columns.Add(sheet.GetRow(0).Cells[j].ToString());}while (rows.MoveNext()){XSSFRow row = (XSSFRow)rows.Current;DataRow dr = dt.NewRow();for (int i = 0; i < row.LastCellNum; i++){NPOI.SS.UserModel.ICell cell = row.GetCell(i);if (cell == null){dr[i] = null;}else{dr[i] = cell.ToString();}}dt.Rows.Add(dr);}dt.Rows.RemoveAt(0);if (dt!=null && dt.Rows.Count != 0){for (int i = 0; i < dt.Rows.Count; i++){string categary = dt.Rows[i]["頁面"].ToString();string fcategary = dt.Rows[i]["分類"].ToString();string fTitle = dt.Rows[i]["標題"].ToString();string fUrl = dt.Rows[i]["鏈接"].ToString();FooterDAL.Addfoot(categary, fcategary, fTitle, fUrl);}}return dt;}#region 兩種不同版本的操作excel///<summary>/// 擴展名*.xls/// </summary>public static DataTable ImExport(DataTable dt, HSSFWorkbook hssfworkbook){// 在webbook中添加一個sheet,對應Excel文件中的sheet,取出第一個工作表,索引是0 NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);System.Collections.IEnumerator rows = sheet.GetRowEnumerator();for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++){dt.Columns.Add(sheet.GetRow(0).Cells[j].ToString());}while (rows.MoveNext()){HSSFRow row = (HSSFRow)rows.Current;DataRow dr = dt.NewRow();for (int i = 0; i < row.LastCellNum; i++){NPOI.SS.UserModel.ICell cell = row.GetCell(i);if (cell == null){dr[i] = null;}else {dr[i] = cell.ToString();}}dt.Rows.Add(dr);}dt.Rows.RemoveAt(0);if (dt != null && dt.Rows.Count != 0){for (int i = 0; i < dt.Rows.Count; i++){string categary = dt.Rows[i]["頁面"].ToString();string fcategary = dt.Rows[i]["分類"].ToString();string fTitle = dt.Rows[i]["標題"].ToString();string fUrl = dt.Rows[i]["鏈接"].ToString();FooterDAL.Addfoot(categary, fcategary, fTitle, fUrl);}}return dt;}#endregion}
}
excelDAL
 public static partial class FooterDAL{/// <summary>/// 添加/// </summary>/// <param name="id"></param>/// <param name="catgary"></param>/// <param name="fcatgary"></param>/// <param name="fTitle"></param>/// <param name="fUrl"></param>/// <returns></returns>public static int  Addfoot(string categary, string fcategary, string fTitle, string fUrl){string sql = string.Format("insert into Foot (categary,fcategary,fTitle,fUrl)values(@categary,@fcategary,@fTitle,@fUrl)");SqlParameter[] parm = { new SqlParameter("@categary",categary),new SqlParameter("@fcategary",fcategary),new SqlParameter("@fTitle",fTitle),new SqlParameter("@fUrl",fUrl)};return new DBHelperSQL<Foot>(CommonTool.dbname).ExcuteSql(sql,parm);   }
}
FooterDAL

//FooterDAL將datatable,就是excel里面的數據添加到sql數據庫

轉載于:https://www.cnblogs.com/wangwangwangMax/p/7922119.html

總結

以上是生活随笔為你收集整理的mvc手把手教你写excel导入的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。