using HighWayIot.Repository.domain;
using HighWayIot.Repository.service;
using Models;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Timer = System.Threading.Timer;
namespace HighWayIot.Winform.Business
{
///
/// 定时报表导出
///
public class TimerExportBusiness
{
private Timer RecordTimer;
private string _savePath = string.Empty;
///
/// 处理前的报表数据
///
private List _zxDailyReportEntities;
///
/// 导出的报表
///
private List _exportTableEntities = new List();
private DataTable dataTable;
public TimerExportBusiness()
{
RecordTimer = new Timer(ExportJudge, null, 0, 1000);
}
///
/// 判断是否该导出了
///
///
private void ExportJudge(object o)
{
DateTime now = DateTime.Now;
var timeList = SysShiftTimeService.Instance.GetShiftInfos();
var morningShift = timeList.Where(x => x.ShiftName == "早").FirstOrDefault();
var startArray = morningShift.ShiftStartTime.Split(':');
if(startArray.Length != 3)
{
return;
}
if (now.Hour == Convert.ToInt32(startArray[0])
&& now.Minute == Convert.ToInt32(startArray[1])
&& now.Second == Convert.ToInt32(startArray[3]))
{
AutoExport();
ZxDailyReportService.Instance.DeleteMoreData();
}
}
private void AutoExport()
{
_savePath = XmlUtil.Instance.ExportPathReader();
//获取前一天的报表
_zxDailyReportEntities = ZxDailyReportService.Instance.GetOneDayDailyReportInfos();
//查询所有称重信息
List _zxWeightEntities = ZxWeightService.Instance.GetWeightInfos();
//查询所有配方信息
List _zxRecipeEntities = ZxRecipeService.Instance.GetRecipeInfos();
//开始关联 生成报表
foreach (ZxDailyReportEntity rawEntity in _zxDailyReportEntities)
{
ExportTableEntity exportTableEntity = new ExportTableEntity();
ZxRecipeEntity recipeEntity = _zxRecipeEntities.Where(x => x.RecipeCode == rawEntity.RecipeCode).FirstOrDefault();
ZxWeightEntity baseWeight = _zxWeightEntities.Where(x => x.RecipeCode == rawEntity.RecipeCode && x.MaterialType == "基部胶").FirstOrDefault();
ZxWeightEntity midWeight = _zxWeightEntities.Where(x => x.RecipeCode == rawEntity.RecipeCode && x.MaterialType == "中层胶").FirstOrDefault();
ZxWeightEntity faceWeight = _zxWeightEntities.Where(x => x.RecipeCode == rawEntity.RecipeCode && x.MaterialType == "胎面胶").FirstOrDefault();
if (recipeEntity == null)
{
continue;
}
exportTableEntity.RecipeCode = rawEntity.RecipeCode;
exportTableEntity.RecipeName = rawEntity.RecipeName;
exportTableEntity.SpecCode = rawEntity.SpecCode;
exportTableEntity.SpecName = recipeEntity.RecipeSpecName;
exportTableEntity.StartTime = rawEntity.StartTime.ToString("yyyy-MM-dd hh:mm:ss");
//基部胶
if (baseWeight != null)
{
exportTableEntity.BaseRubName = baseWeight.MaterialName;
exportTableEntity.BaseRubThickness = baseWeight.SetThickness.ToString();
//基部胶宽度和层数(可能有三层
if (baseWeight.SetLayer2 == 0 || baseWeight.SetLayer2 == null)
{
exportTableEntity.BaseRubWidth = baseWeight.SetWidth.ToString();
exportTableEntity.BaseRubLayer = baseWeight.SetLayer.ToString();
}
else if (baseWeight.SetLayer3 == 0 || baseWeight.SetLayer3 == null)
{
exportTableEntity.BaseRubWidth = $"{baseWeight.SetWidth2}/{baseWeight.SetWidth}";
exportTableEntity.BaseRubLayer = $"{baseWeight.SetLayer2}/{baseWeight.SetLayer}";
}
else
{
exportTableEntity.BaseRubWidth = $"{baseWeight.SetWidth2}/{baseWeight.SetWidth3}/{baseWeight.SetWidth}";
exportTableEntity.BaseRubLayer = $"{baseWeight.SetLayer2}/{baseWeight.SetLayer3}/{baseWeight.SetLayer}";
}
exportTableEntity.BaseRubFinishTime = GeneralUtils.DateTimeToString(rawEntity.StartTime, rawEntity.BaseEndTime);
}
//中层胶
if (midWeight != null)
{
exportTableEntity.MidRubName = midWeight.MaterialName;
exportTableEntity.MidRubThickness = midWeight.SetThickness.ToString();
//中层胶宽度和层数(可能有三层
if (midWeight.SetLayer2 == 0 || midWeight.SetLayer2 == null)
{
exportTableEntity.MidRubWidth = midWeight.SetWidth.ToString();
exportTableEntity.MidRubLayer = midWeight.SetLayer.ToString();
}
else if (midWeight.SetLayer3 == 0 || midWeight.SetLayer3 == null)
{
exportTableEntity.MidRubWidth = $"{midWeight.SetWidth2}/{midWeight.SetWidth}";
exportTableEntity.MidRubLayer = $"{midWeight.SetLayer2}/{midWeight.SetLayer}";
}
else
{
exportTableEntity.MidRubWidth = $"{midWeight.SetWidth2}/{midWeight.SetWidth3}/{midWeight.SetWidth}";
exportTableEntity.MidRubLayer = $"{midWeight.SetLayer2}/{midWeight.SetLayer3}/{midWeight.SetLayer}";
}
exportTableEntity.MidRubFinishTime = GeneralUtils.DateTimeToString(rawEntity.StartTime, rawEntity.MidEndTime);
}
//胎面胶
if (faceWeight != null)
{
exportTableEntity.FaceRubName = faceWeight.MaterialName;
exportTableEntity.FaceRubThickness = faceWeight.SetThickness.ToString();
//胎面胶宽度和层数(可能有三层
if (faceWeight.SetLayer2 == 0 || faceWeight.SetLayer2 == null)
{
exportTableEntity.FaceRubWidth = faceWeight.SetWidth.ToString();
exportTableEntity.FaceRubLayer = faceWeight.SetLayer.ToString();
}
else if (faceWeight.SetLayer3 == 0 || faceWeight.SetLayer3 == null)
{
exportTableEntity.FaceRubWidth = $"{faceWeight.SetWidth2}/{faceWeight.SetWidth}";
exportTableEntity.FaceRubLayer = $"{faceWeight.SetLayer2}/{faceWeight.SetLayer}";
}
else
{
exportTableEntity.FaceRubWidth = $"{faceWeight.SetWidth2}/{faceWeight.SetWidth3}/{faceWeight.SetWidth}";
exportTableEntity.FaceRubLayer = $"{faceWeight.SetLayer2}/{faceWeight.SetLayer3}/{faceWeight.SetLayer}";
}
exportTableEntity.FaceRubFinishTime = GeneralUtils.DateTimeToString(rawEntity.StartTime, rawEntity.FaceEndTime);
}
exportTableEntity.RawTireWidth = (faceWeight.SetThickness * 2 + faceWeight.SetWidth).ToString();
exportTableEntity.StandardWeight = rawEntity.StandardWeight.ToString();
exportTableEntity.RawTireWeight = (rawEntity.RawTireWeight ?? 0).ToString();
exportTableEntity.RepeatWeight = (rawEntity.RepeatWeight ?? 0).ToString();
exportTableEntity.IsDone = rawEntity.IsDone == 1 ? "已完成" : "未完成";
_exportTableEntities.Add(exportTableEntity);
}
try
{
dataTable = ToDataTable(_exportTableEntities.ToArray());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
ExportExcel(dataTable, _savePath);
}
///
/// 导出Excel
///
///
public void ExportExcel(DataTable dt, string path)
{
try
{
//创建一个工作簿
IWorkbook workbook = new HSSFWorkbook();
//创建一个 sheet 表
ISheet sheet = workbook.CreateSheet(dt.TableName);
//创建一行
IRow rowH = sheet.CreateRow(0);
//创建一个单元格
ICell cell = null;
//创建单元格样式
ICellStyle cellStyle = workbook.CreateCellStyle();
//创建格式
IDataFormat dataFormat = workbook.CreateDataFormat();
//设置为文本格式,也可以为 text,即 dataFormat.GetFormat("text");
cellStyle.DataFormat = dataFormat.GetFormat("@");
//设置列名
foreach (DataColumn col in dt.Columns)
{
//创建单元格并设置单元格内容
rowH.CreateCell(col.Ordinal).SetCellValue(col.Caption);
//设置单元格格式
rowH.Cells[col.Ordinal].CellStyle = cellStyle;
}
//写入数据
for (int i = 0; i < dt.Rows.Count; i++)
{
//跳过第一行,第一行为列名
IRow row = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
cell = row.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
cell.CellStyle = cellStyle;
}
}
//设置导出文件路径
//string path = HttpContext.Current.Server.MapPath("Export/");
//设置新建文件路径及名称
string savePath = $"{path}/自动导出-203报表{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}.xls";
//创建文件
FileStream file = new FileStream(savePath, FileMode.CreateNew, FileAccess.Write);
//创建一个 IO 流
MemoryStream ms = new MemoryStream();
//写入到流
workbook.Write(ms);
//转换为字节数组
byte[] bytes = ms.ToArray();
file.Write(bytes, 0, bytes.Length);
file.Flush();
//还可以调用下面的方法,把流输出到浏览器下载
//OutputClient(bytes);
//释放资源
bytes = null;
ms.Close();
ms.Dispose();
file.Close();
file.Dispose();
workbook.Close();
sheet = null;
workbook = null;
MessageBox.Show("导出成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
///
/// 实体类转dt
///
///
///
///
public DataTable ToDataTable(T[] entities)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo propInfo in properties)
{
// Get the Description attribute if it exists
var descriptionAttribute = propInfo.GetCustomAttribute();
string columnName = descriptionAttribute != null ? descriptionAttribute.Description : propInfo.Name;
dataTable.Columns.Add(columnName, propInfo.PropertyType);
}
foreach (T entity in entities)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
}
}