using AutoMapper;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GroupLine.Model;
using NLog;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;
using GroupLine.App.ModelDto;
namespace GroupLine.App.ViewModel
{
public class GInsRotaResViewModel : ViewModelBase
{
//日志的实例化
private static Logger _Logger = LogManager.GetCurrentClassLogger();
private string CurrentMachineName = "G型绝缘、回转方向、电阻测量";
private string CurrentMachineNameTemplate = "GInsRotaResTemplate.xlsx";
private IMapper autoMapper;
///
/// 实例化函数
///
public GInsRotaResViewModel()
{
ListModelDto = new ObservableCollection();
SearchStartDate = DateTime.Now.AddDays(-1).ToShortDateString();
SearchEndDate = DateTime.Now.AddDays(2).ToShortDateString();
MachineName = CurrentMachineName + " - 搜索条件";
var config = new MapperConfiguration(cfg => cfg.CreateMap());
autoMapper = config.CreateMapper();
}
///
/// 列表集合
///
private ObservableCollection _ListModelDto;
///
/// 列表集合
///
public ObservableCollection ListModelDto
{
get { return _ListModelDto; }
set { _ListModelDto = value; }
}
#region "搜索条件属性"
///
/// 机器设备名称
///
private string machineName;
public string MachineName
{
get
{
return machineName;
}
set
{
machineName = value;
RaisePropertyChanged(() => MachineName);
}
}
///
/// 搜索条件-背番号
///
private string searchBackData;
public string SearchBackData
{
get
{
return searchBackData;
}
set
{
searchBackData = value;
RaisePropertyChanged(() => SearchBackData);
}
}
///
/// 搜索条件-筒体编号
///
private string searchCylinderNo;
public string SearchCylinderNo
{
get
{
return searchCylinderNo;
}
set
{
searchCylinderNo = value;
RaisePropertyChanged(() => searchCylinderNo);
}
}
///
/// 搜索条件-开始时间
///
private string searchStartDate;
public string SearchStartDate
{
get
{
return searchStartDate;
}
set
{
searchStartDate = value;
RaisePropertyChanged(() => SearchStartDate);
}
}
///
/// 搜索条件-结束时间
///
private string searchEndDate;
public string SearchEndDate
{
get
{
return searchEndDate;
}
set
{
searchEndDate = value;
RaisePropertyChanged(() => SearchEndDate);
}
}
#endregion
#region "搜索命令"
///
/// 搜索命令
///
private RelayCommand searchCmd;
public RelayCommand SearchCmd
{
get
{
if (searchCmd == null) return new RelayCommand(() => Search());
return searchCmd;
}
set
{
searchCmd = value;
}
}
private void Search()
{
try
{
var MulConQueryable = FSqlContext.FDb.Select();
//多条件查询
if (!string.IsNullOrEmpty(SearchCylinderNo))
{
MulConQueryable = MulConQueryable.Where(t => t.CylinderNo.Contains(SearchCylinderNo));
}
//多条件查询
if (!string.IsNullOrEmpty(SearchStartDate))
{
MulConQueryable = MulConQueryable.Where(t => t.CreateTime.Date >= Convert.ToDateTime(SearchStartDate));
}
//多条件查询
if (!string.IsNullOrEmpty(SearchEndDate))
{
MulConQueryable = MulConQueryable.Where(t => t.CreateTime.Date < Convert.ToDateTime(SearchEndDate).AddDays(1));
}
var ListDpI = MulConQueryable.OrderByDescending(a => a.CreateTime).ToList();//.Where(a => a.CreateTime >= DateTime.Now);
ListModelDto.Clear();
foreach (var item in ListDpI)
{
ListModelDto.Add(autoMapper.Map(item));
}
}
catch (Exception ex)
{
_Logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
}
}
#endregion
#region "导出数据"
//OutputDataCmd
///
/// 搜索命令
///
private RelayCommand _OutputDataCmd;
public RelayCommand OutputDataCmd
{
get
{
if (_OutputDataCmd == null) return new RelayCommand(() => OutputDataAction());
return _OutputDataCmd;
}
set
{
_OutputDataCmd = value;
}
}
private void OutputDataAction()
{
try
{
if (ListModelDto != null && ListModelDto.Count > 0)
{
string FilePath = string.Empty;
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "请选择文件夹";
dialog.ShowNewFolderButton = true; // 显示 新建文件夹 按钮
//dialog.SelectedPath = Environment.CurrentDirectory; // 设置 选择的路径 为 当前项目路径
if (dialog.ShowDialog() == DialogResult.OK)
{
// 判空
if (string.IsNullOrEmpty(dialog.SelectedPath)) { MessageBox.Show("文件夹路径不能为空", "温馨提示", MessageBoxButton.OK, MessageBoxImage.Information); return; }
FilePath = dialog.SelectedPath; // 获取 选择的 文件夹 路径
}
var ListData = ListModelDto.ToList();
/***********************
1.读取excel到workbook中
***********************/
string TemplateFilePath = System.Environment.CurrentDirectory;
string tPath = TemplateFilePath + @"\ReportFile\" + CurrentMachineNameTemplate;
//string tPath = @"D:\ReportTemplate\注油Template.xlsx";
XSSFWorkbook wk = null;
using (FileStream fs = File.Open(tPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
wk = new XSSFWorkbook(fs);
fs.Close(); //把excel里的内容保存到workbook中之后,就可以关闭了
}
NPOI.SS.UserModel.ISheet sheet = wk.GetSheetAt(0); //获得wk中第一个sheet,保存到sheet中
/***********************
2.操作数据
***********************/
//2行 5行
IDataFormat dataformat = wk.CreateDataFormat();
ICellStyle style0 = wk.CreateCellStyle();
ICellStyle styleBag = wk.CreateCellStyle();
styleBag.FillForegroundColor = HSSFColor.Red.Index;
styleBag.FillPattern = FillPattern.SolidForeground;
for (int i = 0; i < ListData.Count; i++)// (int i = 2; i < 6; i += 3)
{
IRow row;
row = sheet.CreateRow(i + 1);
row.CreateCell(0).SetCellValue(ListData[i].CylinderNo.ToString());
row.CreateCell(1).SetCellValue(ListData[i].OpNo.ToString());
row.CreateCell(2).SetCellValue(ListData[i].IsolateResults.ToString());
row.CreateCell(3).SetCellValue(ListData[i].ResValue1.ToString());
row.CreateCell(4).SetCellValue(ListData[i].ResValue2.ToString());
row.CreateCell(5).SetCellValue(ListData[i].ResValue3.ToString());
row.CreateCell(6).SetCellValue(ListData[i].RotaResult.ToString());
row.CreateCell(7).SetCellValue(ListData[i].ResResult.ToString());
row.CreateCell(8).SetCellValue(ListData[i].CreateTime.ToString("yyyy-MM-dd HH:mm"));
//row.GetCell(10).CellStyle = style0;
style0.DataFormat = dataformat.GetFormat("yyyy-MM-dd HH:mm:ss");
row.GetCell(8).CellStyle = style0;
//row.GetCell(26).CellStyle = style0;
//if (ListDat[i].UpperGroupStandDiffResult == "NG")
//{
// row.GetCell(4).CellStyle = styleBag;
//}
//if (ListDat[i].LowerGroupStandDiffResult == "NG")
//{
// row.GetCell(6).CellStyle = styleBag;
//}
//if (ListDat[i].GroupStandDiffResult == "NG")
//{
// row.GetCell(8).CellStyle = styleBag;
//}
//if (ListDat[i].FillReal >= ListDat[i].BeforLow && ListDat[i].FillReal <= ListDat[i].BeforUp)
//{
//}
//else
//{
// row.GetCell(7).CellStyle = styleBag;
//}
}
//DayDailyParameterInfo = null;
//NightDailyParameterInfo = null;
/***********************
3.修改完成,写入到客户端
***********************/
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
//tPath = @"D:\日立报表\";
//判断文件夹是否存在,不存在就创建
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
FilePath = FilePath + @"\" + Convert.ToDateTime(SearchStartDate).ToString("yyyy-MM-dd") + "-" + Convert.ToDateTime(searchEndDate).ToString("yyyy-MM-dd") + "-" + CurrentMachineName + ".xlsx";
wk.Write(ms);
using (FileStream fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
wk = null;
}
System.Windows.MessageBox.Show("生成成功");
}
else
{
MessageBox.Show("请先搜索数据后再导出", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch (Exception ex)
{
_Logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
}
}
#endregion
}
}