亲测可用!微信小程序实现下载预览文件,导出及保存文件及excel
要实现用户导出分页列表数据之后的Excel 并且可以发送及预览功能:
实现方法1:
思路 : 先调用服务器接口,一个返回流的接口之后再用微信官方API接口进行写入文件操作保存指定位置之后进行文档打开预览
实现方法2:
思路 : 先调用服务器接口,一个返回写入文件之后返回保存文件的下载目录URL的接口,之后再用微信官方API接口进行下载操作,下载完成后生成临时缓存目录,保存文件,操作保存指定位置之后进行文档打开预览
以上后端接口都先对列表内容进行读取保存到指定.xls 文件中,需要返回流操作的再次读取返回byte数组或者保存的路径
Excel后端生成插件 EPPlus.dll
官方接口主要有一下几个:
wx.saveFile(Object object)
保存文件到本地。注意:saveFile 会把临时文件移动,因此调用成功后传入的 tempFilePath 将不可用
参数
Object object
属性 类型 默认值 必填 说明
tempFilePath string 是 需要保存的文件的临时路径 (本地路径)
success function 否 接口调用成功的回调函数
fail function 否 接口调用失败的回调函数
complete function 否 接口调用结束的回调函数(调用成功、失败都会执行)
wx.openDocument(Object object)
注意: 新开页面打开文档。微信客户端 7.0.12 版本前默认显示右上角菜单按钮,之后的版本默认不显示,需主动传入 showMenu。
参数
Object object
属性 类型 默认值 必填 说明 最低版本
filePath string 是 文件路径 (本地路径) ,可通过 downloadFile 获得
showMenu boolean false 否 是否显示右上角菜单 2.11.0
fileType string 否 文件类型,指定文件类型打开文件 1.4.0
success function 否 接口调用成功的回调函数
fail function 否 接口调用失败的回调函数
complete function 否 接口调用结束的回调函数(调用成功、失败都会执行)
FileSystemManager.writeFile(Object object)
FileSystemManager.writeFile(Object object)
写文件
参数
Object object
属性 类型 默认值 必填 说明
filePath string 是 要写入的文件路径 (本地路径)
data string/ArrayBuffer 是 要写入的文本或二进制数据
encoding string utf8 否 指定写入文件的字符编码
success function 否 接口调用成功的回调函数
fail function 否 接口调用失败的回调函数
complete function 否 接口调用结束的回调函数(调用成功、失败都会执行)
相关代码:
方法1:
获取流再导出
wx.request({
url: config.BASE_URL + api.ExportManageData, //"/api/ManageBaseDataApp/ExportManageData",
data: JSON.stringify(res),
header: {
"content-type": "application/json",
'Authorization': `bearer ${wx.getStorageSync("access_token")}`
},
method: "POST",
dataType: "json",
responseType: "arraybuffer", //注意这里的responseType
success: (result) => {
console.log("下载成功!", result);
var fileManager = wx.getFileSystemManager();
var FilePath = wx.env.USER_DATA_PATH + "/" + new Date().getTime()+".xls";
fileManager.writeFile({
data: result.data,
filePath: FilePath,
encoding: "binary", //编码方式
success: result => {
wx.openDocument({ //我这里成功之后直接打开
filePath: FilePath,
showMenu:true,
fileType: "xls",
success: result => {
console.log("打开文档成功");
},
fail: err => {
console.log("打开文档失败", err);
}
});
wx.hideLoading();
},
fail: res => {
wx.showToast({
title: '导出失败!',
icon: 'none', //默认值是success,就算没有icon这个值,就算有其他值最终也显示success
duration: 2000, //停留时间
})
console.log(res);
}
})
wx.hideLoading()
},
fail(err) {
console.log(err)
wx.hideLoading()
}
})
方法2:
//先下载URL再导出
var url = api.ExportManageUrl // "/api/ManageBaseDataApp/ExportManageUrl",
var data = JSON.stringify(resData)
https.postAsync(url, data, null).then(result => {
if (result.statusCode == 200 && result.data != "") {
console.log("获取URL成功!", result);
var downLoadUrl = config.BASE_URL + result.data
var fileManager = wx.getFileSystemManager();
var FilePath = wx.env.USER_DATA_PATH + "/" + new Date().getTime() + ".xls";
console.log("开始下载。。", result);
wx.downloadFile({
url: downLoadUrl,
header: {},
success: function (dres) {
console.log("下载成功!");
var tempFilePath = dres.tempFilePath
console.log('临时文件下载地址是:' + tempFilePath)
console.log("下载地址", config.BASE_URL + '/App_Data/dataFile.xls')
var FilePath = wx.env.USER_DATA_PATH + "/" + new Date().toLocaleDateString() + "dataFile.xls";
wx.saveFile({
tempFilePath: tempFilePath,
success: function (sres) {
wx.hideLoading()
console.log("保存成功,地址!", sres)
var saveFilePath = sres.savedFilePath
// var saveFilePath = FilePath
wx.openDocument({
filePath: saveFilePath,
showMenu: true, // 必须写新开页面打开文档。微信客户端 7.0.12 版本前默认显示右上角菜单按钮,之后的版本默认不显示,需主动传入 showMenu
fileType: "xls",
//就是之前的那个saveFilePath
success: function (ores) {
console.log("打开成功!", ores)
}
})
},//可以将saveFilePath写入到页面数据中
fail: function (err) {
wx.showToast({
title: '导出失败!',
icon: 'none',
duration: 1000,
})
console.log("打开失败!", err)
},
complete: function (res) {
console.log('complete后的res数据:')
},
}) //,
},
fail: function (res) {
wx.showToast({
title: '导出失败!',
icon: 'none',
duration: 1000,
})
wx.hideLoading()
},
complete: function (res) { wx.hideLoading() },
})
}
}).catch(err => {
wx.showToast({
title: '导出失败!',
icon: 'none',
duration: 1000,
})
console.log("导出失败!", err)
})
后端代码:
方法1:
public async Task<HttpResponseMessage> ExportManage([FromBody]List<ManageDaoChuModel> parameter)
{
if (!parameter.Any())
return null;
//获得数据
var listData = parameter;
var result = new object();
string sFileName = @"App_Data/excels/dataFile.xlsx";
try
{
string URL = string.Format("{0}://{1}/{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, sFileName);
using (ExcelPackage excelPackage = new ExcelPackage())
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("经营数据");
worksheet.DefaultColWidth =20;
worksheet.Cells[1, 1].Value = "日期";
worksheet.Cells[1, 2].Value = "进场总数(kg)";
worksheet.Cells[1, 3].Value = "进场笔数";
worksheet.Cells[1, 4].Value = "进场总额(元)";
worksheet.Cells[1, 5].Value = "交易总数(kg)";
worksheet.Cells[1, 6].Value = "交易笔数";
worksheet.Cells[1, 7].Value = "交易总额(元)";
var rowNum = 2;
foreach (var queryResult in listData)
{
worksheet.Cells["A" + rowNum].Value = (queryResult.updateDate == null||queryResult.updateDate=="") ? "合计" : queryResult.updateDate;
worksheet.Cells["B" + rowNum].Value = queryResult.weightsIn;
worksheet.Cells["C" + rowNum].Value = queryResult.countsIn;
worksheet.Cells["D" + rowNum].Value = queryResult.totalsIn;
worksheet.Cells["E" + rowNum].Value = queryResult.weightsOut;
worksheet.Cells["F" + rowNum].Value = queryResult.countsOut;
worksheet.Cells["G" + rowNum].Value = queryResult.totalsOut;
rowNum++;
}
using (var cells = worksheet.Cells[1, 1, 1, 7])
{
cells.Style.Font.Bold = true;
cells.Style.Fill.PatternType = ExcelFillStyle.Solid;
cells.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
}
//返回二进制字节数组
result = excelPackage.GetAsByteArray();
byte[] byteres = (byte[])result;
var tm = DateTime.Now.ToShortDateString();
string filePath = HttpContext.Current.Server.MapPath("~/") + "App_Data\\excels\\" + "dataFile.xls";
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(byteres, 0, byteres.Length);
fs.Close();
fs.Dispose();
//excelPackage.Save();
FileStream stream = new FileStream(filePath, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
//fs.Close();
//fs.Dispose();
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel"); //"application/octet-stream"
response.Headers.Add("Access-Control-Expose-Headers", "FileName");
response.Headers.Add("FileName", HttpUtility.UrlEncode("dataFile.xls"));
return response;
}
}
catch (Exception e)
{
LogHelper.Write(e.Message);
throw this.ErrorProcess(e);
}
//return new FileContentResult((byte[])result, "application/x-xls");
}
方法2:
代码
[HttpPost]
public string ExportManageUrl([FromBody]List<ManageDaoChuModel> parameter)
{
if (!parameter.Any())
return null;
//获得数据
var listData = parameter;
var result = new object();
string sFileName = @"App_Data/excels/dataFile.xlsx";
string fileName = "";
string URLS = string.Format("{0}://{1}/{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, sFileName);
try
{
using (ExcelPackage excelPackage = new ExcelPackage())
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("经营数据");
worksheet.DefaultColWidth = 20;
worksheet.Cells[1, 1].Value = "日期";
worksheet.Cells[1, 2].Value = "进场总数(kg)";
worksheet.Cells[1, 3].Value = "进场笔数";
worksheet.Cells[1, 4].Value = "进场总额(元)";
worksheet.Cells[1, 5].Value = "交易总数(kg)";
worksheet.Cells[1, 6].Value = "交易笔数";
worksheet.Cells[1, 7].Value = "交易总额(元)";
var rowNum = 2;
foreach (var queryResult in listData)
{
worksheet.Cells["A" + rowNum].Value = (queryResult.updateDate == null || queryResult.updateDate == "") ? "合计" : queryResult.updateDate;
worksheet.Cells["B" + rowNum].Value = queryResult.weightsIn;
worksheet.Cells["C" + rowNum].Value = queryResult.countsIn;
worksheet.Cells["D" + rowNum].Value = queryResult.totalsIn;
worksheet.Cells["E" + rowNum].Value = queryResult.weightsOut;
worksheet.Cells["F" + rowNum].Value = queryResult.countsOut;
worksheet.Cells["G" + rowNum].Value = queryResult.totalsOut;
rowNum++;
}
using (var cells = worksheet.Cells[1, 1, 1, 7])
{
cells.Style.Font.Bold = true;
cells.Style.Fill.PatternType = ExcelFillStyle.Solid;
cells.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
}
//返回二进制字节数组
result = excelPackage.GetAsByteArray();
byte[] byteres = (byte[])result;
var tm = DateTime.Now.ToString("yyyyMMddhhmmssfff");
var tmpath = DateTime.Now.ToString("yyyyMMdd");
var file = "Files\\" + tmpath +"\\"+ tm + ".xls";
var fileUrl = "/Files/" + tmpath +"/"+ tm + ".xls";
string filePath = HttpContext.Current.Server.MapPath("~/") + file;
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(byteres, 0, byteres.Length);
fs.Close();
fs.Dispose();
fileName = fileUrl;
}
return fileName;
}
catch (Exception e)
{
LogHelper.Write(e.Message);
throw this.ErrorProcess(e);
}
//return new FileContentResult((byte[])result, "application/x-xls");
}
以上第一种方法优缺点 :打开预览文件只能使用wps手机版 ,第二种浏览器wps均可。
以上有什么疑问的也可以私聊我我也是第一次做这种。
下一篇: 32位和64位