下载excel模板,导入数据时需要用到

时间:2023-03-09 02:07:46
下载excel模板,导入数据时需要用到

页面代码:

 <form id="form1" enctype="multipart/form-data">
<div style="float:right">
&nbsp;
<button type="button" class="btn btn-primary" onclick="$('#fileUpload').click()" id="reviewFile">浏览</button>
<button class="btn btn-primary" type="button" style="margin-left:5px;height:30px;" id="dataExport">批量导入</button>
<input type="button" class="btn btn-primary" style="margin-left:5px;height:30px;" id="downLoad" value="下载模板">
</div>
<div style="float:right;margin-top:5px">
<input id="fileUpload" name="fileUpload" type="file" style="display:none" />
<input id="fileText" type="text" class="form-control" disabled />
</div>
<script>
$("#fileUpload").change(function () {
$("#fileText").val($(this).val());
})
</script>
</form>

js代码:

 //下载excel模板
$("#downLoad").click(function () {
//方式1
window.open('/BaseInfoPage/DowntTemplate'); //方式2 此方式还未解锁
//$.ajax({
// url: "/BaseInfoPage/DownLoadExcel", //处理页面的路径
// data: { fileName: "大件运输许可导入模板.xls" }, //要提交的数据是一个JSON
// type: "POST", //提交方式
// dataType: "JSON", //返回数据的类型 //TEXT字符串 JSON返回JSON XML返回XML
// success: function (data) {
// console.log(data);
// },
// error: function (msg) {
// //layer.msg('!', { icon: 1, time: 1000 }, function () { // //});
// //layer.msg(msg, { icon: 2, time: 2000 });
// }
//}) //方式3
//param = "fileName=" + "大件运输许可模板.xls";
//window.location.href = "/BaseInfoPage/DownLoadExcel?" + param;
})

c#后台代码:

      /// <summary>
/// 下载excel模板1
/// </summary>
/// <param name="fileName">文件名</param>
public void DownLoadExcel(string fileName)
{
if (Request.Cookies["LoginValue"] == null) Response.Redirect("../Login/LoginPage"); try
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\ExcelTemplate\\" + fileName + "";//文件路径
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//读取文件路径
byte[] buffer = new byte[fs.Length];
fs.Position = ;
fs.Read(buffer, , (int)fs.Length);
Response.Clear();
Response.AddHeader("Content-Length", fs.Length.ToString());
Response.ContentType = "application/xls";
Response.AddHeader("Content-Disposition", "inline;FileName=大件运输许可导入模板.xls");
fs.Close();
Response.BinaryWrite(buffer);
Response.OutputStream.Flush();
Response.OutputStream.Close();
//Response.OutputStream.Write(buffer, 0, (int)fs.Length);
}
catch (Exception ex)
{
CSysCfg.WriteLog("获取文档异常:" + ex.Message);
} }
/// 下载excel模板2
public ActionResult DowntTemplate(HttpPostedFileBase file)
{
//模板文件的路径
string filePath = Server.MapPath("~/ExcelTemplate/大件运输许可导入模板.xls");////获取文件路径
if (System.IO.File.Exists(filePath))
{
string strfileName = Path.GetFileName(filePath);//获取文件名称
return File(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), "application/octet-stream", strfileName);
}
else
{
return Content("模板文件找不到!请检查文件是否存在!");//提示用户
}
}