Commit 669cc6a7 authored by 黄奎's avatar 黄奎

111

parent 1703ac07
...@@ -417,6 +417,195 @@ namespace Mall.Common.Plugin ...@@ -417,6 +417,195 @@ namespace Mall.Common.Plugin
return ms.ToArray(); return ms.ToArray();
} }
} }
/// <summary>
/// 模板导出
/// </summary>
/// <param name="list">模板数据</param>
/// <param name="isTempLate">是否模板导出</param>
/// <param name="tempLatePath">模板文件路劲</param>
public static byte[] ToBrandExcelExtend(List<ExcelDataSource> list, string filepath)
{
HSSFWorkbook workbook = null;
HSSFSheet sheet;
workbook = new HSSFWorkbook();
sheet = workbook.CreateSheet() as HSSFSheet;
int rowIndex = 0;
HSSFFont ffont = (HSSFFont)workbook.CreateFont();
//单元格样式
HSSFCellStyle fCellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
//循环添加行
foreach (var item in list)
{
HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
if (item.ColumnHight > 0)
{
dataRow.Height = (short)(item.ColumnHight * 10);//行高
}
else
{
dataRow.Height = 50 * 10;//行高
}
int columnsIndex = 0;
//循环添加列
foreach (var subItem in item.ExcelRows)
{
if (subItem.Pic == 1 && !string.IsNullOrWhiteSpace(subItem.Value))
{
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
try
{
string fileName = System.IO.Path.GetFileName(subItem.Value);
string newPath = filepath + fileName;
byte[] bytes = System.IO.File.ReadAllBytes(newPath);
int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, columnsIndex, rowIndex, columnsIndex + 1, rowIndex + 1);
//把图片插到相应的位置
HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
}
catch
{
}
columnsIndex++;
}
else
{
var cell = dataRow.CreateCell(columnsIndex);
fCellStyle.WrapText = true;
//设置单元宽度
if (subItem.CellWidth > 0)
{
sheet.SetColumnWidth(columnsIndex, subItem.CellWidth * 256);
}
//设置单元格背景颜色
switch (subItem.BgColorEnum)
{
case ColorEnum.BrightGreen:
fCellStyle.FillForegroundColor = HSSFColor.BrightGreen.Index;
fCellStyle.FillPattern = FillPattern.SolidForeground;
break;
case ColorEnum.DarkBlue:
fCellStyle.FillForegroundColor = HSSFColor.DarkBlue.Index;
fCellStyle.FillPattern = FillPattern.SolidForeground;
break;
case ColorEnum.Red:
fCellStyle.FillForegroundColor = HSSFColor.Red.Index;
fCellStyle.FillPattern = FillPattern.SolidForeground;
break;
}
if (subItem.FontHeight > 0)
{
ffont.FontHeight = subItem.FontHeight * 20;
}
else
{
ffont.FontHeight = 11 * 20;
}
if (!string.IsNullOrWhiteSpace(subItem.FontName))
{
ffont.FontName = subItem.FontName;
}
else
{
ffont.FontName = "宋体";
}
if (subItem.FontSize > 0)
{
ffont.FontHeightInPoints = subItem.FontSize;
}
//设置字体颜色
switch (subItem.FontColorEnum)
{
case ColorEnum.Red:
ffont.Color = HSSFColor.Red.Index;
break;
case ColorEnum.Green:
ffont.Color = HSSFColor.Green.Index;
break;
}
//字体加粗
if (subItem.IsBold)
{
ffont.IsBold = subItem.IsBold;
}
fCellStyle.SetFont(ffont);
//水平对齐方式
fCellStyle.Alignment = subItem.HAlignmentEnum switch
{
HAlignmentEnum.CENTER => HorizontalAlignment.Center,
HAlignmentEnum.LEFT => HorizontalAlignment.Left,
HAlignmentEnum.RIGHT => HorizontalAlignment.Right,
_ => HorizontalAlignment.Center,
};
//垂直对齐方式
fCellStyle.VerticalAlignment = subItem.VAlignmentEnum switch
{
VAlignmentEnum.CENTER => VerticalAlignment.Center,
VAlignmentEnum.TOP => VerticalAlignment.Top,
VAlignmentEnum.BOTTOM => VerticalAlignment.Bottom,
_ => VerticalAlignment.Center,
};
if (!subItem.IsSetBorder)
{
fCellStyle.BorderBottom = BorderStyle.Thin;
fCellStyle.BorderLeft = BorderStyle.Thin;
fCellStyle.BorderRight = BorderStyle.Thin;
fCellStyle.BorderTop = BorderStyle.Thin;
}
else
{
fCellStyle.BorderBottom = BorderStyle.None;
fCellStyle.BorderLeft = BorderStyle.None;
fCellStyle.BorderRight = BorderStyle.None;
fCellStyle.BorderTop = BorderStyle.None;
}
//合并单元格
if (subItem.Colspan > 1 || subItem.Rowspan > 1)
{
var region = new CellRangeAddress(rowIndex, rowIndex + (subItem.Rowspan - 1), columnsIndex, columnsIndex + (subItem.Colspan - 1));
sheet.AddMergedRegion(region);
for (int i = region.FirstRow; i <= region.LastRow; i++)
{
IRow row = CellUtil.GetRow(i, sheet);
for (int j = region.FirstColumn; j <= region.LastColumn; j++)
{
ICell singleCell = CellUtil.GetCell(row, (short)j);
singleCell.CellStyle = fCellStyle;
}
}
columnsIndex += subItem.Colspan;
}
else
{
cell.CellStyle = fCellStyle;
columnsIndex++;
}
cell.SetCellValue(subItem.Value ?? "");
}
}
rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
return ms.ToArray();
}
}
} }
......
...@@ -3,6 +3,7 @@ using System.Collections.Generic; ...@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Collections.Specialized; using System.Collections.Specialized;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Web; using System.Web;
...@@ -21,6 +22,7 @@ using Microsoft.AspNetCore.Cors; ...@@ -21,6 +22,7 @@ using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using SharpCompress.Common; using SharpCompress.Common;
namespace Mall.WebApi.Controllers.TradePavilion namespace Mall.WebApi.Controllers.TradePavilion
...@@ -2168,7 +2170,7 @@ namespace Mall.WebApi.Controllers.TradePavilion ...@@ -2168,7 +2170,7 @@ namespace Mall.WebApi.Controllers.TradePavilion
if (string.IsNullOrEmpty(redisValue)) if (string.IsNullOrEmpty(redisValue))
{ {
redisHelper.StringSet(key, fileName, TimeSpan.FromMinutes(30)); redisHelper.StringSet(key, fileName, TimeSpan.FromMinutes(30));
GetBrandListToExcel(demodel, ExcelEnumIds, fileUrl); GetBrandListToExcel(demodel, ExcelEnumIds, tempPath, fileUrl);
} }
} }
return await Task.Run<ApiResult>(() => return await Task.Run<ApiResult>(() =>
...@@ -2179,8 +2181,10 @@ namespace Mall.WebApi.Controllers.TradePavilion ...@@ -2179,8 +2181,10 @@ namespace Mall.WebApi.Controllers.TradePavilion
}; };
if (System.IO.File.Exists(fileUrl)) if (System.IO.File.Exists(fileUrl))
{ {
var filePath = "/upfile/temporary/" + hashKey + "/";
var fileUrl = "/upfile/temporary/" + hashKey + "/" + fileName;
apiResult.resultCode = 1; apiResult.resultCode = 1;
apiResult.data = "/upfile/temporary/" + hashKey + "/" + fileName; apiResult.data = new { filePath, fileUrl };
apiResult.message = key; apiResult.message = key;
} }
return apiResult; return apiResult;
...@@ -2197,13 +2201,18 @@ namespace Mall.WebApi.Controllers.TradePavilion ...@@ -2197,13 +2201,18 @@ namespace Mall.WebApi.Controllers.TradePavilion
JObject parms = JObject.Parse(RequestParm.msg.ToString()); JObject parms = JObject.Parse(RequestParm.msg.ToString());
string key = parms.GetStringValue("key"); string key = parms.GetStringValue("key");
string fileUrl = parms.GetStringValue("fileUrl"); string fileUrl = parms.GetStringValue("fileUrl");
string newPath = Directory.GetCurrentDirectory() + fileUrl; string filepath = parms.GetStringValue("filepath");
string newPath = Directory.GetCurrentDirectory() + filepath;
try try
{ {
if (System.IO.File.Exists(newPath)) if (Directory.Exists(newPath))
{ {
System.IO.File.Delete(newPath); Directory.Delete(newPath, true);
} }
//if (System.IO.File.Exists(newPath))
//{
// System.IO.File.Delete(newPath);
//}
redisHelper.KeyDelete(key); redisHelper.KeyDelete(key);
} }
catch (Exception ex) catch (Exception ex)
...@@ -2239,7 +2248,7 @@ namespace Mall.WebApi.Controllers.TradePavilion ...@@ -2239,7 +2248,7 @@ namespace Mall.WebApi.Controllers.TradePavilion
/// 品牌下载 /// 品牌下载
/// </summary> /// </summary>
private void GetBrandListToExcel(RB_Brand_Extend demodel, List<int> ExcelEnumIds, string excelFileUrl) private void GetBrandListToExcel(RB_Brand_Extend demodel, List<int> ExcelEnumIds,string filePath, string excelFileUrl)
{ {
try try
{ {
...@@ -2282,8 +2291,25 @@ namespace Mall.WebApi.Controllers.TradePavilion ...@@ -2282,8 +2291,25 @@ namespace Mall.WebApi.Controllers.TradePavilion
try try
{ {
List<Action> actions = new List<Action>();
var list = carrierModule.GetBrandListByWhere(demodel); var list = carrierModule.GetBrandListByWhere(demodel);
if (list != null && list.Count > 0)
{
foreach (var item in list)
{
actions.Add(new Action(() =>
{
DownLoadUrl(item.Logo, filePath);
}));
}
}
if (actions != null && actions.Count > 0)
{
ParallelOptions options = new ParallelOptions { MaxDegreeOfParallelism = 4 }; // 设置最大并行度为 4
Parallel.Invoke(options, actions.ToArray());
}
#region 组装数据 #region 组装数据
int Num = 0; int Num = 0;
foreach (var item in list) foreach (var item in list)
...@@ -2350,7 +2376,7 @@ namespace Mall.WebApi.Controllers.TradePavilion ...@@ -2350,7 +2376,7 @@ namespace Mall.WebApi.Controllers.TradePavilion
slist.Add(datarow); slist.Add(datarow);
} }
#endregion #endregion
bytes = ExcelTempLateHelper.ToExcelExtend(slist); bytes = ExcelTempLateHelper.ToBrandExcelExtend(slist, filePath);
using (FileStream fs = new FileStream(excelFileUrl, FileMode.CreateNew)) using (FileStream fs = new FileStream(excelFileUrl, FileMode.CreateNew))
{ {
fs.Write(bytes, 0, bytes.Length); fs.Write(bytes, 0, bytes.Length);
...@@ -2358,7 +2384,7 @@ namespace Mall.WebApi.Controllers.TradePavilion ...@@ -2358,7 +2384,7 @@ namespace Mall.WebApi.Controllers.TradePavilion
} }
catch (Exception ex) catch (Exception ex)
{ {
bytes = ExcelTempLateHelper.ToExcelExtend(slist); bytes = ExcelTempLateHelper.ToBrandExcelExtend(slist, filePath);
using (FileStream fs = new FileStream(excelFileUrl, FileMode.CreateNew)) using (FileStream fs = new FileStream(excelFileUrl, FileMode.CreateNew))
{ {
fs.Write(bytes, 0, bytes.Length); fs.Write(bytes, 0, bytes.Length);
...@@ -2367,6 +2393,43 @@ namespace Mall.WebApi.Controllers.TradePavilion ...@@ -2367,6 +2393,43 @@ namespace Mall.WebApi.Controllers.TradePavilion
} }
} }
/// <summary>
/// 下载文件
/// </summary>
private void DownLoadUrl(string url, string savePath)
{
Uri uri = new Uri(url);
string path = uri.AbsolutePath;
int lastSlashIndex = path.LastIndexOf('/');
string fileName = path.Substring(lastSlashIndex + 1);
string newFilePath = savePath + fileName;
string logStr = string.Format("{0} 开始下载 Url_{1} 文件 ", DateTime.Now.ToString("MM-dd HH:mm:ss fff"), url);
Console.WriteLine(logStr);
LogHelper.WriteInfo(logStr);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 1000 * 60 * 20; // 10分钟超时时间
using (WebResponse response = request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (Stream fileStream = new FileStream(newFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
responseStream.CopyTo(fileStream);
}
}
catch (Exception ex)
{
logStr = string.Format("{0} 下载 Url_{1} 异常:{2} message:{3}", DateTime.Now.ToString("MM-dd HH:mm:ss fff"), url, ex.StackTrace, ex.Message);
Console.WriteLine(logStr);
LogHelper.WriteInfo(logStr);
}
logStr = string.Format("{0} 下载 Url_{1} 文件结束 ", DateTime.Now.ToString("MM-dd HH:mm:ss fff"), url);
Console.WriteLine(logStr);
LogHelper.WriteInfo(logStr);
}
/// <summary> /// <summary>
/// 获取品牌下载枚举列表 /// 获取品牌下载枚举列表
/// </summary> /// </summary>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment