導入導出對於剛做的人一臉懵逼,但是明白思路之後就感覺非常容易,我也是研究了好久,才總算做了出來,放在這裡給大家分享一下 一.先看下導出 視圖腳本 視圖html代碼 控制器代碼 二,從Excel導入資料庫 視圖代碼 控制器代碼 public ActionResult Show(HttpPostedFi ...
導入導出對於剛做的人一臉懵逼,但是明白思路之後就感覺非常容易,我也是研究了好久,才總算做了出來,放在這裡給大家分享一下
一.先看下導出
視圖腳本
<script type ="text/javascript" language="javascript"> function selectExcel() { var GUID = document.getElementsByName("check"); var temp = ""; var strGUID = ""; for (var i = 0; i < GUID.length; i++) { if (GUID[i].checked) { temp += GUID[i].value + ","; } } strGUID = temp //alert(strGUID);//測試取到的值是否正確 alert(strGUID); //$("#GUID").val(strGUID);//將多選的值賦給Id為strGUID的隱藏域 document.getElementById("strGUID").value = strGUID; } </script>
視圖html代碼
@using (Html.BeginForm("DataIn", "Home", FormMethod.Post)) { <table> <tr> <td>@Html.Hidden("strGUID")</td> <td><input type="submit" value="導出" onclick="selectExcel()" /></td> </tr> </table> }
控制器代碼
public ActionResult DataTableToExcel(string strGUID) { string[] GUID = Request.Form["strGUID"].Split(','); //這個是讀取要導出的列表,邏輯要自己寫的 DataTable dt = new DataTable(); dt.Columns.Add("序號"); dt.Columns.Add("姓名"); foreach (var aa in GUID) { if(aa!=null&& aa!="") { int id=Convert.ToInt32(aa); //List<User> list = db.user.Where(p => p.Uid == id).ToList(); User model = db.user.Find(id); dt.Rows.Add(model.Uid,model.Uname); } } //= SQLServerDAL.DSalesOrders.SalesOrders_GetListExcel(strGUID).Tables[0]; System.Web.UI.WebControls.DataGrid dgExport = null; // 當前對話 System.Web.HttpContext curContext = System.Web.HttpContext.Current; // IO用於導出並返回excel文件 System.IO.StringWriter strWriter = null; System.Web.UI.HtmlTextWriter htmlWriter = null; string filename = DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute; byte[] str = null; if (dt != null) { // 設置編碼和附件格式 curContext.Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//設置輸出流為簡體中文 curContext.Response.ContentType = "application/vnd.ms-excel"; //System.Text.Encoding.UTF8; // 導出excel文件 strWriter = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); //// 為瞭解決dgData中可能進行了分頁的情況,需要重新定義一個無分頁的DataGrid dgExport = new System.Web.UI.WebControls.DataGrid(); dgExport.DataSource = dt.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); dgExport.RenderControl(htmlWriter); // 返回客戶端 str = System.Text.Encoding.UTF8.GetBytes(strWriter.ToString()); } return File(str, "attachment;filename=" + filename + ".xls"); } <!--如果報格式亂碼錯誤 把設置編碼和附件格式下的代碼換成下麵代碼--> curContext.Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); curContext.Response.ContentEncoding = Encoding.Default;//設置輸出流為簡體中文 curContext.Response.ContentType = "application/vnd.ms-excel"; Response.Write("<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=utf-8\"/>");//加上這句話string類型就不亂碼了
二,從Excel導入資料庫
視圖代碼
@using (Html.BeginForm("Show", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <p> 選擇文件:<input id="FileUpload" type="file" name="files" style="width: 250px; height: 24px; background: White" class="easyui-validatebox" /> </p> <p> <input id="btnImport" type="submit" value="導入" style="width: 60px; height: 28px;" /> </p> }
控制器代碼
public ActionResult Show(HttpPostedFileBase filebase)
{
HttpPostedFileBase file=Request.Files["files"];
string FileName;
string savePath;
if (file == null||file.ContentLength<=0)
{
ViewBag.error = "文件不能為空";
return View();
}
else
{
string filename= Path.GetFileName(file.FileName);
int filesize = file.ContentLength;//獲取上傳文件的大小單位為位元組byte
string fileEx = System.IO.Path.GetExtension(filename);//獲取上傳文件的擴展名
string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//獲取無擴展名的文件名
int Maxsize = 4000 * 1024;//定義上傳文件的最大空間大小為4M
string FileType = ".xls,.xlsx";//定義上傳文件的類型字元串
FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
if (!FileType.Contains(fileEx))
{
ViewBag.error = "文件類型不對,只能導入xls和xlsx格式的文件";
return View();
}
if (filesize >= Maxsize)
{
ViewBag.error = "上傳文件超過4M,不能上傳";
return View();
}
string path = AppDomain.CurrentDomain.BaseDirectory + "Excel/";
savePath = Path.Combine(path, FileName);
file.SaveAs(savePath);
}
//string result = string.Empty;
string strConn;
strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + savePath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", strConn);
DataSet myDataSet = new DataSet();
try
{
myCommand.Fill(myDataSet, "ExcelInfo");
}
catch (Exception ex)
{
ViewBag.error = ex.Message;
return View();
}
DataTable table = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
//引用事務機制,出錯時,事物回滾
using (TransactionScope transaction = new TransactionScope())
{
for (int i = 0; i < table.Rows.Count; i++)
{
////獲取地區名稱
//string _areaName = table.Rows[i][0].ToString();
////判斷地區是否存在
//if (!_areaRepository.CheckAreaExist(_areaName))
//{
// ViewBag.error = "導入的文件中:" + _areaName + "地區不存在,請先添加該地區";
// return View();
//}
//else
//{
// Station station = new Station();
// station.AreaID = _areaRepository.GetIdByAreaName(_areaName).AreaID;
// station.StationName = table.Rows[i][1].ToString();
// station.TerminaAddress = table.Rows[i][2].ToString();
// station.CapacityGrade = table.Rows[i][3].ToString();
// station.OilEngineCapacity = decimal.Parse(table.Rows[i][4].ToString());
// _stationRepository.AddStation(station);
//}
User model = new User();
model.Uname = table.Rows[i][0].ToString();
db.user.Add(model);
db.SaveChanges();
}
transaction.Complete();
}
ViewBag.error = "導入成功";
System.Threading.Thread.Sleep(2000);
return Content("<script>alert('數據導入成功!');location.href='/Home/Index'</script>");
}
三:註意,
導出中的事務機制需要引用 using System.Transactions;
若是沒有添加這個.dll組件可以去程式集中添加引用