d_sms_service/APT.Utility/FileUtils.cs
2024-10-28 13:45:58 +08:00

982 lines
41 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace APT.Utility
{
public class FileUtils
{
/// <summary>
/// 读取Excel文件第一个Sheet保存到DataTable中
/// </summary>
/// <param name="fileNamePath"></param>
/// <param name="startRowIndexs">开始行项索引</param>
/// <returns></returns>
public static DataTable ReadExcelTable(string fileNamePath, int startRowIndex)
{
try
{
Dictionary<int, int> startRowIndexs = new Dictionary<int, int>();
startRowIndexs[0] = startRowIndex;
var ds = ReadExcelByOledb(fileNamePath, startRowIndexs);
if (ds != null && ds.Tables.Count > 0)
return ds.Tables[0];
}
catch
{
}
return null;
}
/// <summary>
/// 实际读取EXCELsheet
/// </summary>
/// <param name="workbook"></param>
/// <param name="index"></param>
/// <returns></returns>
private static DataTable DoReadExcelByOledb(IWorkbook workbook, int index, int startRowIndex)
{
DataTable dt = new DataTable();
ISheet sheet = workbook.GetSheetAt(index);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rfirst = startRowIndex > 0 ? startRowIndex - 1 : sheet.FirstRowNum;
int rlast = sheet.LastRowNum;
if (rlast == 0)
throw new Exception($"工作簿索引[{index}]的行数据为0请确认");
IRow row = sheet.GetRow(rfirst);
int cfirst = row.FirstCellNum;
int clast = row.LastCellNum;
//获取sheet页中表的字段值
for (int i = cfirst; i < clast; i++)
{
if (row.GetCell(i) != null)
{
var cell = row.GetCell(i);
if (cell.CellType == CellType.Numeric)
{
//NPOI中数字和日期都是NUMERIC类型的这里对其进行判断是否是日期类型
if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型
{
dt.Columns.Add(cell.DateCellValue.ToString(), System.Type.GetType("System.String"));
}
else//其他数字类型
{
dt.Columns.Add(cell.NumericCellValue.ToString(), System.Type.GetType("System.String"));
}
}
else if (cell.CellType == CellType.Blank)//空数据类型
{
dt.Columns.Add("", System.Type.GetType("System.String"));
}
else if (cell.CellType == CellType.Formula)//公式类型
{
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(workbook);
dt.Columns.Add(eva.Evaluate(cell).StringValue, System.Type.GetType("System.String"));
}
else //其他类型都按字符串类型来处理
{
dt.Columns.Add(cell.StringCellValue, System.Type.GetType("System.String"));
}
}
}
row = null;
//获取sheet页中表的数据值
for (int i = rfirst + 1; i <= rlast; i++)
{
IRow ir = sheet.GetRow(i);
if (ir == null) continue;
DataRow r = dt.NewRow();
for (int j = cfirst; j < clast; j++)
{
var val = "";
if (ir.GetCell(j) != null)
{
try
{
var cell = ir.GetCell(j);
if (cell.CellType == CellType.Numeric)
{
//NPOI中数字和日期都是NUMERIC类型的这里对其进行判断是否是日期类型
if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型
{
val = cell.DateCellValue.ToString();
}
else//其他数字类型
{
val = cell.NumericCellValue.ToString();
}
}
else if (cell.CellType == CellType.Blank)//空数据类型
{
}
else if (cell.CellType == CellType.Formula)//公式类型
{
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(workbook);
val = eva.Evaluate(cell).StringValue;
}
else //其他类型都按字符串类型来处理
{
val = cell.StringCellValue;
}
r[j] = val;
}
catch (Exception ex)
{
throw new Exception($"数据读取异常,行:{i + 1},列{j + 1},错误详情:{ex.Message}");
}
}
else
{
r[j] = val; //wyw 某个空格没数据
}
}
dt.Rows.Add(r);
}
return dt;
}
/// <summary>
/// Oledb方式读取EXCEL
/// </summary>
/// <param name="fileNamePath">文件路径</param>
/// <returns></returns>
public static DataSet ReadExcelByOledb(string fileNamePath, Dictionary<int, int> startRowIndexs)
{
if (!File.Exists(fileNamePath)) return null;
var extendName = System.IO.Path.GetExtension(fileNamePath);
string connStr = "";
if (extendName == "xlsx")
{
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileNamePath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
}
else
{
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + fileNamePath;
}
DataSet dataSet = new DataSet();
// 读取Excel到DataSet
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
if (!startRowIndexs.ContainsKey(i))
continue;
int startIndex = 0;
if (startRowIndexs != null)
startRowIndexs.TryGetValue(i, out startIndex);
var t = DoReadExcelByOledb(workbook, i, startIndex);
if (t != null)
dataSet.Tables.Add(t);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return dataSet;
}
/// <summary>
/// 特殊导入页面处理
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
public static List<ImportTempData> ReadExcelByImport(string fileNamePath)
{
List<ImportTempData> importTempDatas = new List<ImportTempData>();
if (!File.Exists(fileNamePath)) return null;
string connStr = "";
var extendName = System.IO.Path.GetExtension(fileNamePath);
if (extendName == ".xlsx")
{
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileNamePath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
}
else
{
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + fileNamePath;
}
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
int startIndex = 0;
importTempDatas = DoReadExcelImport(workbook, i, startIndex);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return importTempDatas;
}
private static List<ImportTempData> DoReadExcelImport(IWorkbook workbook, int index, int startRowIndex)
{
List<ImportTempData> tempDatas = new List<ImportTempData>();
ISheet sheet = workbook.GetSheetAt(index);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rfirst = startRowIndex > 0 ? startRowIndex - 1 : sheet.FirstRowNum;//行首
int rlast = sheet.LastRowNum;//行尾
if (rlast == 0)
throw new Exception($"工作簿索引[{index}]的行数据为0请确认");
IRow row = sheet.GetRow(rfirst);
int cfirst = row.FirstCellNum;//第一行第一列
int clast = row.LastCellNum;//第一行第三列
for (int i = rfirst + 2; i <= rlast; i++)//第三行数据
{
IRow ir = sheet.GetRow(1);
IRow ir1 = sheet.GetRow(i);
for (int j = 0; j < ir.Cells.Count; j++)
{
ImportTempData tempData = new ImportTempData();
tempData.START_TIME = row.GetCell(2).StringCellValue + "-" + (ir.Cells[j].StringCellValue.Length < 2 ? "0" + ir.Cells[j].StringCellValue : ir.Cells[j].StringCellValue);
tempData.Name = ir1.Cells[1].ToString();
tempData.QTY = ir1.Cells[j + 2].ToString();
tempDatas.Add(tempData);
}
}
return tempDatas;
}
#region
/// <summary>
/// 历史数据导入页面处理
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
public static List<ImportHistData> ReadExcelByImportHistData(string fileNamePath)
{
List<ImportHistData> importHistDatas = new List<ImportHistData>();
if (!File.Exists(fileNamePath)) return null;
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
int startIndex = 2;
DoReadExcelImportHistData(workbook, i, startIndex, importHistDatas);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return importHistDatas;
}
private static List<ImportHistData> DoReadExcelImportHistData(IWorkbook workbook, int index, int startRowIndex, List<ImportHistData> histDatas)
{
ISheet sheet = workbook.GetSheetAt(index);
DataTable dt = DoReadExcelByOledb(workbook, index, startRowIndex);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rfirst = startRowIndex > 0 ? startRowIndex - 1 : sheet.FirstRowNum;//行首
int rlast = sheet.LastRowNum;//行尾
if (rlast < 2)
throw new Exception("工作簿中的数据为空,请确认!" + index);
IRow row = sheet.GetRow(rfirst + 1);
int cfirst = row.FirstCellNum;
int clast = row.LastCellNum;
var timeStr = sheet.GetRow(1).GetCell(4).StringCellValue;
var sTime = DateTime.Parse(timeStr);
for (int i = rfirst - 1; i <= rlast - 2; i++)//第三行数据
{
var nTime = sTime;
DataRow ir = dt.Rows[i];
if (ir.Table.Rows.Count > 0)
{
for (int j = 4; j < clast; j++)
{
if (ir[j]?.ToString().Length != 0)
{
ImportHistData tempData = new ImportHistData
{
Name = ir[0].ToString(),
Time = nTime,
Data = decimal.Parse(ir[j].ToString()),
};
histDatas.Add(tempData);
}
nTime = nTime.AddMonths(1);
}
}
else break;
}
return histDatas;
}
#endregion
#region
/// <summary>
/// 年抄表卡数据导入页面处理
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
public static List<ImportMeterReadData> ReadExcelByImportYearMeterReadData(string fileNamePath)
{
List<ImportMeterReadData> importMeterReadDatas = new List<ImportMeterReadData>();
if (!File.Exists(fileNamePath)) return null;
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
int startIndex = 2;
DoReadExcelImportYearMeterReadData(workbook, i, startIndex, importMeterReadDatas);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return importMeterReadDatas;
}
private static List<ImportMeterReadData> DoReadExcelImportYearMeterReadData(IWorkbook workbook, int index, int startRowIndex, List<ImportMeterReadData> importMeterReadDatas)
{
ISheet sheet = workbook.GetSheetAt(index);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rfirst = startRowIndex > 0 ? startRowIndex - 1 : sheet.FirstRowNum;//行首
int rlast = sheet.LastRowNum;//行尾
if (rlast < 2)
throw new Exception("工作簿中的数据为空,请确认!" + index);
DataTable dt = DoReadExcelByOledb(workbook, index, startRowIndex);
IRow row = sheet.GetRow(rfirst + 1);
int clast = row.LastCellNum; //列尾
var timeStr = sheet.GetRow(1).GetCell(4).StringCellValue;
var sTime = DateTime.Parse(timeStr);
for (int i = rfirst - 1; i <= rlast - 2; i++)//第三行数据
{
var nTime = sTime;
DataRow ir = dt.Rows[i];
if (ir.Table.Rows.Count > 0)
{
for (int j = 4; j < clast; j++)
{
if (ir[j]?.ToString().Length > 0)
{
ImportMeterReadData meterReadData = new ImportMeterReadData
{
Name = ir[0].ToString(),
Data = decimal.Parse(ir[j].ToString()),
Time = nTime,
};
if (meterReadData.Name == null)
throw new Exception($"第{i + 1}行的器具为空,导入失败");
importMeterReadDatas.Add(meterReadData);
}
nTime = nTime.AddMonths(1);
}
}
else break;
}
return importMeterReadDatas;
}
/// <summary>
/// 月抄表卡数据导入页面处理
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
public static List<ImportMeterReadData> ReadExcelByImportMonthMeterReadData(string fileNamePath)
{
List<ImportMeterReadData> importMeterReadDatas = new List<ImportMeterReadData>();
if (!File.Exists(fileNamePath)) return null;
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
int startIndex = 2;
DoReadExcelImportMonthMeterReadData(workbook, i, startIndex, importMeterReadDatas);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return importMeterReadDatas;
}
private static List<ImportMeterReadData> DoReadExcelImportMonthMeterReadData(IWorkbook workbook, int index, int startRowIndex, List<ImportMeterReadData> importMeterReadDatas)
{
ISheet sheet = workbook.GetSheetAt(index);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rfirst = startRowIndex > 0 ? startRowIndex - 1 : sheet.FirstRowNum;//行首
int rlast = sheet.LastRowNum;//行尾
if (rlast < 2)
throw new Exception("工作簿中的数据为空,请确认!" + index);
IRow row = sheet.GetRow(rfirst + 1);
int clast = row.LastCellNum;
DataTable dt = DoReadExcelByOledb(workbook, index, startRowIndex);
var timeStr = sheet.GetRow(1).GetCell(4).StringCellValue;
var sTime = DateTime.Parse(timeStr);
for (int i = rfirst - 1; i <= rlast - 2; i++)//第三行数据
{
var nTime = sTime;
DataRow ir = dt.Rows[i];
if (ir.Table.Rows.Count > 0)
{
for (int j = 4; j < clast; j++)
{
if (ir[j]?.ToString().Length > 0)
{
ImportMeterReadData meterReadData = new ImportMeterReadData
{
Name = ir[0].ToString(),
Data = decimal.Parse(ir[j].ToString()),
Time = nTime,
};
if (meterReadData.Name == null)
throw new Exception($"第{i + 1}行的器具为空,导入失败");
importMeterReadDatas.Add(meterReadData);
}
nTime = nTime.AddDays(1);
}
}
else break;
}
return importMeterReadDatas;
}
/// <summary>
/// 日抄表卡数据导入页面处理
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
public static List<ImportMeterReadData> ReadExcelByImportDayMeterReadData(string fileNamePath)
{
List<ImportMeterReadData> importMeterReadDatas = new List<ImportMeterReadData>();
if (!File.Exists(fileNamePath)) return null;
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
int startIndex = 2;
DoReadExcelImportDayMeterReadData(workbook, i, startIndex, importMeterReadDatas);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return importMeterReadDatas;
}
private static List<ImportMeterReadData> DoReadExcelImportDayMeterReadData(IWorkbook workbook, int index, int startRowIndex, List<ImportMeterReadData> importMeterReadDatas)
{
ISheet sheet = workbook.GetSheetAt(index);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rfirst = startRowIndex > 0 ? startRowIndex - 1 : sheet.FirstRowNum;//行首
int rlast = sheet.LastRowNum;//行尾
if (rlast < 2)
throw new Exception("工作簿中的数据为空,请确认!" + index);
IRow row = sheet.GetRow(rfirst + 1);
int clast = row.LastCellNum;
DataTable dt = DoReadExcelByOledb(workbook, index, startRowIndex);
var timeStr = sheet.GetRow(1).GetCell(4).StringCellValue;
var sTime = DateTime.Parse(timeStr);
for (int i = rfirst - 1; i <= rlast - 2; i++)//第三行数据
{
var nTime = sTime;
DataRow ir = dt.Rows[i];
if (ir.Table.Rows.Count > 0)
{
for (int j = 4; j < clast; j++)
{
if (ir[j]?.ToString().Length > 0)
{
ImportMeterReadData meterReadData = new ImportMeterReadData
{
Name = ir[0].ToString(),
Data = decimal.Parse(ir[j].ToString()),
Time = nTime,
};
if (meterReadData.Name == null)
throw new Exception($"第{i + 1}行的器具为空,导入失败");
importMeterReadDatas.Add(meterReadData);
}
nTime = nTime.AddHours(1);
}
}
else break;
}
return importMeterReadDatas;
}
#endregion
#region
/// <summary>
/// 生产记录数据导入页面处理
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
public static List<ImportProductRecordData> ReadExcelByImportProductRecordData(string fileNamePath)
{
List<ImportProductRecordData> importMeterReadDatas = new List<ImportProductRecordData>();
if (!File.Exists(fileNamePath)) return null;
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
int startIndex = 2;
DoReadExcelImportProductRecordData(workbook, i, startIndex, importMeterReadDatas);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return importMeterReadDatas;
}
private static List<ImportProductRecordData> DoReadExcelImportProductRecordData(IWorkbook workbook, int index, int startRowIndex, List<ImportProductRecordData> importMeterReadDatas)
{
ISheet sheet = workbook.GetSheetAt(index);
DataTable dt = DoReadExcelByOledb(workbook, index, startRowIndex);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rfirst = startRowIndex > 0 ? startRowIndex - 1 : sheet.FirstRowNum;//行首
int rlast = sheet.LastRowNum;//行尾
if (rlast < 2)
throw new Exception("工作簿中的数据为空,请确认!" + index);
IRow row = sheet.GetRow(rfirst + 1);
for (int i = rfirst - 1; i <= rlast - 2; i++)//第三行数据
{
DataRow ir = dt.Rows[i];
if (ir.Table.Rows.Count > 0)
{
var meterReadData = new ImportProductRecordData()
{
Product_Code = ir[0].ToString(),
Product_Name = ir[1].ToString(),
MeterNode_Name = ir[2].ToString(),
Team_Name = ir[3].ToString(),
Class_Name = ir[4].ToString(),
Qty = decimal.Parse(ir[5].ToString()),
Start_Time = DateTime.Parse(ir[6].ToString()),
End_Time = DateTime.Parse(ir[7].ToString()),
Modify_Time = DateTime.Parse(ir[8].ToString()),
Order_Status = ir[9].ToString(),
Remark = ir.Table.Rows.Count == 10 ? "" : ir[10].ToString(),
};
importMeterReadDatas.Add(meterReadData);
}
else break;
}
return importMeterReadDatas;
}
#endregion
#region
/// <summary>
/// 能源采购导入页面处理
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
public static List<ImportEnergyPurchaseData> ReadExcelByImportEnergyPurchaseData(string fileNamePath)
{
List<ImportEnergyPurchaseData> importEnergyPurchaseDatas = new List<ImportEnergyPurchaseData>();
if (!File.Exists(fileNamePath)) return null;
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
int startIndex = 2;
DoReadExcelImportEnergyPurchaseData(workbook, i, startIndex, importEnergyPurchaseDatas);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return importEnergyPurchaseDatas;
}
private static List<ImportEnergyPurchaseData> DoReadExcelImportEnergyPurchaseData(IWorkbook workbook, int index, int startRowIndex, List<ImportEnergyPurchaseData> importEnergyPurchaseDatas)
{
ISheet sheet = workbook.GetSheetAt(index);
DataTable dt = DoReadExcelByOledb(workbook, index, startRowIndex);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rfirst = startRowIndex > 0 ? startRowIndex - 1 : sheet.FirstRowNum;//行首
int rlast = sheet.LastRowNum;//行尾
if (rlast < 2)
throw new Exception("工作簿中的数据为空,请确认!" + index);
IRow row = sheet.GetRow(rfirst + 1);
for (int i = rfirst - 1; i <= rlast - 2; i++)//第三行数据
{
DataRow ir = dt.Rows[i];
if (ir.Table.Rows.Count > 0)
{
var EnergyPurchaseData = new ImportEnergyPurchaseData()
{
Energy_Name = ir[0].ToString(),
Qty = decimal.Parse(ir[3].ToString()),
Batch = ir[4].ToString(),
Plan_Date = DateTime.Parse(ir[5].ToString()),
};
importEnergyPurchaseDatas.Add(EnergyPurchaseData);
}
else break;
}
return importEnergyPurchaseDatas;
}
#endregion
#region
/// <summary>
/// 生产记录导入
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
public static List<ImportProductRecordData> ReadExcelByImportProductionRecords(string fileNamePath)
{
var importMeterReadDatas = new List<ImportProductRecordData>();
if (!File.Exists(fileNamePath)) return null;
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
int startIndex = 3;
DoReadExcelImportProductionRecords(workbook, i, startIndex, importMeterReadDatas);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return importMeterReadDatas;
}
private static void DoReadExcelImportProductionRecords(IWorkbook workbook, int index, int startRowIndex, List<ImportProductRecordData> importMeterReadDatas)
{
ISheet sheet = workbook.GetSheetAt(index);
DataTable dt = DoReadExcelByOledb(workbook, index, startRowIndex);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rlast = sheet.LastRowNum;//行尾
if (rlast < startRowIndex)
throw new Exception("工作簿中的数据为空,请确认!" + index);
IRow row = sheet.GetRow(1);
var nodeName = row.Cells[0].ToString();
var cloumn = sheet.GetRow(2).Cells;
for (int i = 0; i < dt.Rows.Count; i++)//第三行数据
{
DataRow ir = dt.Rows[i];
if (string.IsNullOrEmpty(ir[0].ToString()))
continue;
var items = GetTimeRatio(ir[0].ToString(), ir[1].ToString().Split(','));
var total = items.Sum(x => x.Minute);
foreach (var item in items)
{
for (int j = 5; j < cloumn.Count; j++)
{
var model = new ImportProductRecordData
{
Product_Name = cloumn[j].ToString(),
MeterNode_Name = nodeName,
Class_Name = ir[2].ToString(),
Team_Name = ir[3].ToString(),
Start_Time = item.StartTime,
End_Time = item.EndTime
};
if (items.Count > 1)
{
var qty = decimal.Parse(ir[j].ToString());
var workHour = decimal.Parse(ir[4].ToString());
var ratio = total == 0 ? 0 : item.Minute / total;
model.Qty = qty * ratio;
model.WorkHour = workHour * ratio;
}
else
{
model.Qty = decimal.Parse(ir[j].ToString());
model.WorkHour = decimal.Parse(ir[4].ToString());
}
importMeterReadDatas.Add(model);
}
}
}
}
private static List<TimeRatio> GetTimeRatio(string date, string[] array)
{
var list = new List<TimeRatio>();
foreach (var item in array)
{
var split = item.Split('-');
var st = DateTime.Parse($"{date} {split[0]}");
var et = DateTime.Parse($"{date} {split[1]}");
var minute = (et - st).TotalMinutes;
list.Add(new TimeRatio { StartTime = st, EndTime = et, Minute = (decimal)minute });
}
return list;
}
#region
public static List<ImportDeptRecordData> ReadExcelByImportDeptRecords(string fileNamePath)
{
var importDeptReadDatas = new List<ImportDeptRecordData>();
if (!File.Exists(fileNamePath)) return null;
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
int startIndex = 3;
DoReadExcelImportDeptRecords(workbook, i, startIndex, importDeptReadDatas);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return importDeptReadDatas;
}
private static void DoReadExcelImportDeptRecords(IWorkbook workbook, int index, int startRowIndex, List<ImportDeptRecordData> importDeptReadDatas)
{
ISheet sheet = workbook.GetSheetAt(index);
DataTable dt = DoReadExcelByOledb(workbook, index, startRowIndex);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rlast = sheet.LastRowNum;//行尾
if (rlast < startRowIndex)
throw new Exception("工作簿中的数据为空,请确认!" + index);
IRow row = sheet.GetRow(1);
var nodeName = row.Cells[0].ToString();
var cloumn = sheet.GetRow(2).Cells;
for (int i = 0; i < dt.Rows.Count; i++)//第三行数据
{
DataRow ir = dt.Rows[i];
if (string.IsNullOrEmpty(ir[0].ToString()))
continue;
for (int colIndex = 1; colIndex < cloumn.Count; colIndex++)
{
var model = new ImportDeptRecordData
{
Equip_Name = ir[0].ToString(),
Dept_Name = nodeName,
Qty = decimal.Parse(ir[colIndex].ToString()),
Time = Convert.ToDateTime(cloumn[colIndex].ToString())
};
importDeptReadDatas.Add(model);
}
}
}
#endregion
#endregion
#region
/// <summary>
/// 生产计划导入
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
public static List<ImportProductPlanData> ReadExcelByImportProductionPlans(string fileNamePath)
{
var importMeterReadDatas = new List<ImportProductPlanData>();
if (!File.Exists(fileNamePath)) return null;
using (FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (fileNamePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileNamePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
try
{
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
int startIndex = 3;
DoReadExcelImportProductionPlans(workbook, i, startIndex, importMeterReadDatas);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
fs.Close();
}
return importMeterReadDatas;
}
private static void DoReadExcelImportProductionPlans(IWorkbook workbook, int index, int startRowIndex, List<ImportProductPlanData> importMeterReadDatas)
{
ISheet sheet = workbook.GetSheetAt(index);
DataTable dt = DoReadExcelByOledb(workbook, index, startRowIndex);
if (sheet == null)
throw new Exception("获取不到工作簿,工作簿索引:" + index);
int rlast = sheet.LastRowNum;//行尾
if (rlast < startRowIndex)
throw new Exception("工作簿中的数据为空,请确认!" + index);
IRow row = sheet.GetRow(1);
var nodeName = row.Cells[0].ToString();
var cloumn = sheet.GetRow(2).Cells;
for (int i = 0; i < dt.Rows.Count; i++)//第三行数据
{
DataRow ir = dt.Rows[i];
if (string.IsNullOrEmpty(ir[0].ToString()))
continue;
for (int j = 1; j < cloumn.Count; j++)
{
var model = new ImportProductPlanData
{
Product_Name = cloumn[j].ToString(),
MeterNode_Name = nodeName,
Start_Time = Convert.ToDateTime(ir[0].ToString() + " 00:00:00"),
End_Time = Convert.ToDateTime(ir[0].ToString() + " 23:59:59"),
Qty = decimal.Parse(ir[j].ToString() == "" ? "0" : ir[j].ToString())
};
importMeterReadDatas.Add(model);
}
}
}
#endregion
#region
#endregion
}
public class TimeRatio
{
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
/// <summary>
/// 间隔分钟数
/// </summary>
public decimal Minute { get; set; }
}
}