添加项目文件。

This commit is contained in:
liming 蔡
2026-07-14 13:55:17 +08:00
parent 63759495f2
commit 8bbdf78731
335 changed files with 81415 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JY.Utility
{
public class CSVHelper<T>
{
/// <summary>
/// 读取CSV文件
/// </summary>
/// <param name="fileName">csv文件名</param>
/// <returns></returns>
public static List<T> ReadCSV(string fileName, string strSeparator = "\t")
{
if (!File.Exists(fileName)) return null;
//Nuget获取CsvHelper
using (var reader = new StreamReader(fileName))
{
var cfg = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
{
Mode = CsvMode.Escape,
Escape = '\\',
Delimiter = strSeparator//设置分隔符号
};
using (var csv = new CsvReader(reader, cfg))
{
var list = csv.GetRecords<T>().ToList();
return list;
}
}
}
}
}
+132
View File
@@ -0,0 +1,132 @@
using System.Drawing;
using System.Windows.Forms.DataVisualization.Charting;
namespace JY.Utility
{
public class ChartHelper
{
/// <summary>
/// Name:添加序列
///
/// </summary>
/// <param name="chart">图表对象</param>
/// <param name="seriesName">序列名称</param>
/// <param name="chartType">图表类型</param>
/// <param name="color">颜色</param>
/// <param name="markColor">标记点颜色</param>
/// <param name="showValue">是否显示数值</param>
public static void AddSeries(Chart chart, string seriesName, SeriesChartType chartType, Color color, Color markColor, bool showValue = false)
{
chart.Series.Add(seriesName);
chart.Series[seriesName].ChartType = chartType;
chart.Series[seriesName].Color = color;
if (showValue)
{
chart.Series[seriesName].IsValueShownAsLabel = true;
chart.Series[seriesName].MarkerStyle = MarkerStyle.Circle;
chart.Series[seriesName].MarkerColor = markColor;
chart.Series[seriesName].LabelForeColor = color;
chart.Series[seriesName].LabelAngle = -90;
}
}
/// <summary>
/// Name:设置标题
///
/// </summary>
/// <param name="chart">图表对象</param>
/// <param name="chartName">图表名称</param>
public static void SetTitle(Chart chart, string chartName, Font font, Docking docking, Color foreColor)
{
chart.Titles.Add(chartName);
chart.Titles[0].Font = font;
chart.Titles[0].Docking = docking;
chart.Titles[0].ForeColor = foreColor;
}
/// <summary>
/// Name:设置样式
/// 2019-04-23 14:04
/// </summary>
/// <param name="chart">图表对象</param>
/// <param name="backColor">背景颜色</param>
/// <param name="foreColor">字体颜色</param>
public static void SetStyle(Chart chart, Color backColor, Color foreColor)
{
chart.BackColor = backColor;
chart.ChartAreas[0].BackColor = backColor;
chart.ForeColor = Color.Red;
}
/// <summary>
/// Name:设置图例
/// Author:
/// </summary>
/// <param name="chart">图表对象</param>
/// <param name="docking">停靠位置</param>
/// <param name="align">对齐方式</param>
/// <param name="backColor">背景颜色</param>
/// <param name="foreColor">字体颜色</param>
public static void SetLegend(Chart chart, Docking docking, StringAlignment align, Color backColor, Color foreColor)
{
chart.Legends[0].Docking = docking;
chart.Legends[0].Alignment = align;
chart.Legends[0].BackColor = backColor;
chart.Legends[0].ForeColor = foreColor;
}
/// <summary>
/// Name:设置XY轴
/// Author:
/// </summary>
/// <param name="chart">图表对象</param>
/// <param name="xTitle">X轴标题</param>
/// <param name="yTitle">Y轴标题</param>
/// <param name="align">坐标轴标题对齐方式</param>
/// <param name="foreColor">坐标轴字体颜色</param>
/// <param name="lineColor">坐标轴颜色</param>
/// <param name="arrowStyle">坐标轴箭头样式</param>
/// <param name="xInterval">X轴的间距</param>
/// <param name="yInterval">Y轴的间距</param>
public static void SetXY(Chart chart, string xTitle, string yTitle, StringAlignment align, Color foreColor, Color lineColor, AxisArrowStyle arrowStyle, double xInterval, double yInterval)
{
//chart.ChartAreas[0].AxisX.Title = xTitle;
//chart.ChartAreas[0].AxisY.Title = yTitle;
//chart.ChartAreas[0].AxisX.TitleAlignment = align;
//chart.ChartAreas[0].AxisY.TitleAlignment = align;
chart.ChartAreas[0].AxisX.TitleForeColor = foreColor;
chart.ChartAreas[0].AxisY.TitleForeColor = foreColor;
chart.ChartAreas[0].AxisX.LabelStyle = new LabelStyle() { ForeColor = foreColor };
chart.ChartAreas[0].AxisY.LabelStyle = new LabelStyle() { ForeColor = foreColor };
chart.ChartAreas[0].AxisX.LineColor = lineColor;
chart.ChartAreas[0].AxisY.LineColor = lineColor;
chart.ChartAreas[0].AxisY.LabelStyle.ForeColor = lineColor;
chart.ChartAreas[0].AxisX.LabelStyle.ForeColor = lineColor;
chart.ChartAreas[0].AxisX.ArrowStyle = arrowStyle;
chart.ChartAreas[0].AxisY.ArrowStyle = arrowStyle;
chart.ChartAreas[0].AxisX.Interval = xInterval;
// chart.ChartAreas[0].AxisY.Interval = yInterval;
}
/// <summary>
/// Name:设置网格
/// Author:
/// </summary>
/// <param name="chart">图表对象</param>
/// <param name="lineColor">网格线颜色</param>
/// <param name="xInterval">X轴网格的间距</param>
/// <param name="yInterval">Y轴网格的间距</param>
public static void SetMajorGrid(Chart chart, Color lineColor, double xInterval, double yInterval)
{
chart.ChartAreas[0].AxisX.MajorGrid.LineColor = lineColor;
chart.ChartAreas[0].AxisY.MajorGrid.LineColor = lineColor;
chart.ChartAreas[0].AxisX.MajorGrid.Interval = xInterval;
chart.ChartAreas[0].AxisY.MajorGrid.Interval = yInterval;
}
}
}
+54
View File
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JY.Utility
{
public class ConvertHelper
{
/// <summary>
/// DateTime转long
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static long DateTimeToLong(DateTime dt)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
TimeSpan toNow = dt.Subtract(dtStart);
long timeStamp = toNow.Ticks;
timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
return timeStamp;
}
/// <summary>
/// 字符串转数字
/// </summary>
/// <param name="strData"></param>
/// <returns></returns>
public static Decimal StringToDecimal(string strData)
{
Decimal dData = 0.0M;
try
{
if (strData.ToUpper().Contains("E"))
{
dData = Convert.ToDecimal(Decimal.Parse(strData.ToString(), System.Globalization.NumberStyles.Float).ToString("f4"));
}
else
{
dData = Convert.ToDecimal(Decimal.Parse(strData).ToString("f4"));
}
if (dData > 10000000000)
{
return 0.00M;
}
}
catch
{ }
return dData;
}
}
}
+115
View File
@@ -0,0 +1,115 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace JY.Utility
{
public static class CustomAttributeHelper
{
/// <summary>
/// Cache Data
/// </summary>
private static readonly Dictionary<string, string> Cache = new Dictionary<string, string>();
/// <summary>
/// 获取CustomAttribute Value
/// </summary>
/// <typeparam name="T">Attribute的子类型</typeparam>
/// <param name="sourceType">头部标有CustomAttribute类的类型</param>
/// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
/// <returns>返回Attribute的值,没有则返回null</returns>
public static string GetCustomAttributeValue<T>(this Type sourceType, Func<T, string> attributeValueAction) where T : Attribute
{
return GetAttributeValue(sourceType, attributeValueAction, null);
}
/// <summary>
/// 获取CustomAttribute Value
/// </summary>
/// <typeparam name="T">Attribute的子类型</typeparam>
/// <param name="sourceType">头部标有CustomAttribute类的类型</param>
/// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
/// <param name="name">field name或property name</param>
/// <returns>返回Attribute的值,没有则返回null</returns>
public static string GetCustomAttributeValue<T>(this Type sourceType, Func<T, string> attributeValueAction,
string name) where T : Attribute
{
return GetAttributeValue(sourceType, attributeValueAction, name);
}
private static string GetAttributeValue<T>(Type sourceType, Func<T, string> attributeValueAction,
string name) where T : Attribute
{
var key = BuildKey(sourceType, name);
if (!Cache.ContainsKey(key))
{
CacheAttributeValue(sourceType, attributeValueAction, name);
}
return Cache[key];
}
/// <summary>
/// 缓存Attribute Value
/// </summary>
private static void CacheAttributeValue<T>(Type type,
Func<T, string> attributeValueAction, string name)
{
var key = BuildKey(type, name);
var value = GetValue(type, attributeValueAction, name);
lock (key + "_attributeValueLockKey")
{
if (!Cache.ContainsKey(key))
{
Cache[key] = value;
}
}
}
private static string GetValue<T>(Type type,
Func<T, string> attributeValueAction, string name)
{
object attribute = null;
if (string.IsNullOrEmpty(name))
{
attribute =
type.GetCustomAttributes(typeof(T), false).FirstOrDefault();
}
else
{
var propertyInfo = type.GetProperty(name);
if (propertyInfo != null)
{
attribute =
propertyInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
}
var fieldInfo = type.GetField(name);
if (fieldInfo != null)
{
attribute = fieldInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
}
}
return attribute == null ? null : attributeValueAction((T)attribute);
}
/// <summary>
/// 缓存Collection Name Key
/// </summary>
private static string BuildKey(Type type, string name)
{
if (string.IsNullOrEmpty(name))
{
return type.FullName;
}
return type.FullName + "." + name;
}
}
}
+99
View File
@@ -0,0 +1,99 @@
namespace JY.Utility
{
public class DataList
{
private string g1;
private string g2;
private string g3;
private string g4;
private string g5;
private string g6;
private string g7;
private string g8;
public string G1
{
get
{
return g1;
}
set
{
g1 = value;
}
}
public string G2
{
get
{
return g2;
}
set
{
g2 = value;
}
}
public string G3
{
get
{
return g3;
}
set
{
g3 = value;
}
}
public string G4
{
get
{
return g4;
}
set
{
g4 = value;
}
}
public string G5
{
get
{
return g5;
}
set
{
g5 = value;
}
}
public string G6
{
get
{
return g6;
}
set
{
g6 = value;
}
}
public string G7
{
get
{
return g7;
}
set
{
g7 = value;
}
}
}
}
+379
View File
@@ -0,0 +1,379 @@
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using OfficeOpenXml.Style;
namespace JY.Utility
{
public class EPPlusExcelHelper : IDisposable
{
public ExcelPackage ExcelPackage { get; private set; }
private Stream fs;
public EPPlusExcelHelper(string filePath)
{
if (File.Exists(filePath))
{
var file = new FileInfo(filePath);
ExcelPackage = new ExcelPackage(file);
}
else
{
fs = File.Create(filePath);
ExcelPackage = new ExcelPackage(fs);
}
}
/// <summary>
/// 将List集合导出到Excel中
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="sheetName"></param>
public void ExportList<T>(IEnumerable<T> list, string sheetName = "")
{
if (string.IsNullOrEmpty(sheetName))
{
sheetName = ExcelPackage.File.Name;
}
AppendSheetToWorkBook(list, sheetName);
Save();
}
/// <summary>
/// 将List集合导出到Excel中
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <param name="sheetName"></param>
public void ExportDataTable(string strFileName,DataTable dt)
{
AppendSheetToWorkBook(strFileName,dt);
Save();
}
/// <summary>
/// 获取sheet,没有则创建
/// </summary>
/// <param name="sheetName"></param>
/// <returns></returns>
public ExcelWorksheet GetOrAddSheet(string sheetName)
{
ExcelWorksheet ws = ExcelPackage.Workbook.Worksheets.FirstOrDefault(i => i.Name == sheetName);
if (ws == null)
{
ws = ExcelPackage.Workbook.Worksheets.Add(sheetName);
}
return ws;
}
/// <summary>
/// DataTable数据导出到Excel(xlsx)
/// </summary>
/// <param name="ExcelPackage">ExcelPackage</param>
/// <param name="sourceTable">数据源</param>
public void AppendSheetToWorkBook(string strFileName,DataTable sourceTable)
{
AppendSheetToWorkBook(strFileName,sourceTable, true);
}
/// <summary>
/// DataTable数据导出到Excel(xlsx)
/// </summary>
/// <param name="ExcelPackage">ExcelPackage</param>
/// <param name="sourceTable">数据源</param>
/// <param name="isDeleteSameNameSheet">是否删除同名的sheet</param>
public void AppendSheetToWorkBook(string strFileName,DataTable sourceTable, bool isDeleteSameNameSheet)
{
//创建worksheet
ExcelWorksheet ws = AddSheet(strFileName, isDeleteSameNameSheet);
//ExcelWorksheet ws = AddSheet(sourceTable.TableName, isDeleteSameNameSheet);
//从单元格A1开始,将数据表加载到工作表中。第1行输出列名
ws.Cells["A1"].LoadFromDataTable(sourceTable, true);
//格式化Row
FromatRow(sourceTable.Rows.Count, sourceTable.Columns.Count, ws);
}
/// <summary>
/// 删除指定的sheet
/// </summary>
/// <param name="ExcelPackage"></param>
/// <param name="sheetName"></param>
public void DeleteSheet(string sheetName)
{
var sheet = ExcelPackage.Workbook.Worksheets.FirstOrDefault(i => i.Name == sheetName);
if (sheet != null)
{
ExcelPackage.Workbook.Worksheets.Delete(sheet);
}
}
/// <summary>
/// 导出列表到excel,已存在同名sheet将删除已存在的
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ExcelPackage"></param>
/// <param name="list">数据源</param>
/// <param name="sheetName">sheet名称</param>
public void AppendSheetToWorkBook<T>(IEnumerable<T> list, string sheetName)
{
AppendSheetToWorkBook(list, sheetName, true);
}
/// <summary>
/// 导出列表到excel,已存在同名sheet将删除已存在的
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ExcelPackage"></param>
/// <param name="list">数据源</param>
/// <param name="sheetName">sheet名称</param>
/// <param name="isDeleteSameNameSheet">是否删除已存在的同名sheet,false时将重命名导出的sheet</param>
public void AppendSheetToWorkBook<T>(IEnumerable<T> list, string sheetName, bool isDeleteSameNameSheet)
{
ExcelWorksheet ws = AddSheet(sheetName, isDeleteSameNameSheet);
ws.Cells["A1"].LoadFromCollection(list, true);
}
/// <summary>
/// 添加文字图片
/// </summary>
/// <param name="sheet"></param>
/// <param name="msg">要转换成图片的文字</param>
public void AddPicture(string sheetName, string msg)
{
Bitmap img = GetPictureString(msg);
var sheet = GetOrAddSheet(sheetName);
var picName = "92FF5CFE-2C1D-4A6B-92C6-661BDB9ED016";
var pic = sheet.Drawings.FirstOrDefault(i => i.Name == picName);
if (pic != null)
{
sheet.Drawings.Remove(pic);
}
pic = sheet.Drawings.AddPicture(picName, msg);
pic.SetPosition(3, 0, 6, 0);
}
/// <summary>
/// 文字绘制图片
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
private static Bitmap GetPictureString(string msg)
{
var msgs = msg.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
var maxLenght = msgs.Max(i => i.Length);
var rowCount = msgs.Count();
var rowHeight = 23;
var fontWidth = 17;
var img = new Bitmap(maxLenght * fontWidth, rowCount * rowHeight);
using (Graphics g = Graphics.FromImage(img))
{
g.Clear(Color.White);
Font font = new Font("Arial", 12, (FontStyle.Bold));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.Blue, Color.DarkRed, 1.2f, true);
for (int i = 0; i < msgs.Count(); i++)
{
g.DrawString(msgs[i], font, brush, 3, 2 + rowHeight * i);
}
}
return img;
}
/// <summary>
/// List转DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public DataTable ListToDataTable<T>(IEnumerable<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dataTable = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
/// <summary>
/// 插入行
/// </summary>
/// <param name="sheet"></param>
/// <param name="values">行类容,一个单元格一个对象</param>
/// <param name="rowIndex">插入位置,起始位置为1</param>
public void InsertValues(string sheetName, List<object> values, int rowIndex)
{
var sheet = GetOrAddSheet(sheetName);
sheet.InsertRow(rowIndex, 1);
int i = 1;
foreach (var item in values)
{
sheet.SetValue(rowIndex, i, item);
i++;
}
}
/// <summary>
/// 保存修改
/// </summary>
public void Save()
{
try
{
ExcelPackage.Save();
ExcelPackage.Stream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 添加Sheet到ExcelPackage
/// </summary>
/// <param name="ExcelPackage">ExcelPackage</param>
/// <param name="sheetName">sheet名称</param>
/// <param name="isDeleteSameNameSheet">如果存在同名的sheet是否删除</param>
/// <returns></returns>
private ExcelWorksheet AddSheet(string sheetName, bool isDeleteSameNameSheet)
{
if (isDeleteSameNameSheet)
{
DeleteSheet(sheetName);
}
else
{
while (ExcelPackage.Workbook.Worksheets.Any(i => i.Name == sheetName))
{
sheetName = sheetName + "(1)";
}
}
ExcelWorksheet ws = ExcelPackage.Workbook.Worksheets.Add(sheetName);
return ws;
}
private void FromatRow(int rowCount, int colCount, ExcelWorksheet ws)
{
ExcelBorderStyle borderStyle = ExcelBorderStyle.Thin;
Color borderColor = Color.FromArgb(155, 155, 155);
using (ExcelRange rng = ws.Cells[1, 1, rowCount + 1, colCount])
{
rng.Style.Font.Name = "宋体";
rng.Style.Font.Size = 10;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //设置图案的背景为Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(255, 255, 255));
rng.Style.Border.Top.Style = borderStyle;
rng.Style.Border.Top.Color.SetColor(borderColor);
rng.Style.Border.Bottom.Style = borderStyle;
rng.Style.Border.Bottom.Color.SetColor(borderColor);
rng.Style.Border.Right.Style = borderStyle;
rng.Style.Border.Right.Color.SetColor(borderColor);
}
// 格式化标题行
using (ExcelRange rng = ws.Cells[1, 1, 1, colCount])
{
rng.Style.Font.Bold = true;
rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(234, 241, 246));
rng.Style.Font.Color.SetColor(Color.FromArgb(51, 51, 51));
}
}
/// <summary>
/// <summary>
/// 导入Excel(EPPlus只支持.xlsx)
/// </summary>
/// <param name="sheetindex">第几个Sheet</param>
/// <returns></returns>
public DataTable ImportExcel(int sheetindex = 1)
{
DataSet ds = new DataSet();
using (ExcelWorksheet worksheet = ExcelPackage.Workbook.Worksheets[sheetindex])
{
if (worksheet.Dimension == null)
{
return null;
}
DataTable table = new DataTable(worksheet.Name);
for (int rowNum = 1; rowNum <= worksheet.Dimension.End.Row; rowNum++)
{
#region 创建列
if (table.Columns.Count == 0)
{
#region 第一行数据作为表头
for (int columnNum = 1; columnNum <= worksheet.Dimension.End.Column; columnNum++)
{
table.Columns.Add(worksheet.Cells[rowNum, columnNum].Value.ToString().Trim(), typeof(string));
}
continue;
#endregion
}
#endregion
#region 新增行
DataRow dr = table.NewRow();
for (int columnNum = 1; columnNum <= table.Columns.Count; columnNum++)
{
if (worksheet.Cells[rowNum, columnNum].Value==null)
{
dr[columnNum - 1] =string.Empty;
}
else
{
dr[columnNum - 1] = worksheet.Cells[rowNum, columnNum].Value.ToString().Trim();
}
}
table.Rows.Add(dr);
#endregion
}
return table;
}
}
public void Dispose()
{
ExcelPackage.Dispose();
if (fs != null)
{
fs.Dispose();
fs.Close();
}
}
}
}
+92
View File
@@ -0,0 +1,92 @@
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
namespace JY.Utility
{
public static class ExcelImporter
{
public static List<T> Import<T>(string filePath, string sheetName = "Sheet1") where T : new()
{
// 设置 LicenseContext(非商业用途)
ExcelPackage.License.SetNonCommercialPersonal("EVE");
if (!File.Exists(filePath))
{
throw new FileNotFoundException("Excel文件不存在", filePath);
}
var result = new List<T>();
var fileInfo = new FileInfo(filePath);
using (var package = new ExcelPackage(fileInfo))
{
var worksheet = package.Workbook.Worksheets.FirstOrDefault(w => w.Name.Equals(sheetName, StringComparison.OrdinalIgnoreCase));
if (worksheet == null)
{
throw new ArgumentException($"指定的工作表 '{sheetName}' 不存在");
}
if (worksheet.Dimension == null)
{
return result;
}
var dimension = worksheet.Dimension;
var headers = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (int col = dimension.Start.Column; col <= dimension.End.Column; col++)
{
var headerValue = worksheet.Cells[1, col].Value?.ToString().Trim();
if (!string.IsNullOrEmpty(headerValue))
{
headers[headerValue] = col;
}
}
var properties = TypeDescriptor.GetProperties(typeof(T));
for (int row = dimension.Start.Row + 1; row <= dimension.End.Row; row++)
{
var item = new T();
bool hasData = false;
foreach (PropertyDescriptor property in properties)
{
if (headers.TryGetValue(property.Description, out int col))
{
var cellValue = worksheet.Cells[row, col].Value;
if (cellValue != null)
{
hasData = true;
var stringValue = cellValue.ToString().Trim();
try
{
var targetType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
var convertedValue = Convert.ChangeType(stringValue, targetType);
property.SetValue(item, convertedValue);
}
catch
{
property.SetValue(item, null);
}
}
}
}
if (hasData)
{
result.Add(item);
}
}
}
return result;
}
}
}
+79
View File
@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace JY.Utility
{
public class IniFileHelper
{
private static string iniFilePath = "ComConfig.ini";
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
public static string ReadIniData(string Section, string Key)
{
try
{
if (File.Exists(iniFilePath))
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, Key, "", temp, 1024, iniFilePath);
return temp.ToString();
}
MessageBox.Show("节点:" + Section + ",键名:" + Key + ":读取配置文件错误!");
return null;
}
catch
{
throw;
}
}
public static bool WriteIniData(string Section, string Key, string Value)
{
try
{
if (File.Exists(iniFilePath))
{
if (WritePrivateProfileString(Section, Key, Value, iniFilePath) == 0L)
{
return false;
}
return true;
}
File.Create(iniFilePath).Close();
if (WritePrivateProfileString(Section, Key, Value, iniFilePath) == 0L)
{
return false;
}
return true;
}
catch
{
throw;
}
}
public static void CreateIniFile(string StartupPath, string AppName)
{
iniFilePath = StartupPath + AppName;
if (!Directory.Exists(StartupPath))
{
Directory.CreateDirectory(StartupPath);
}
if (!File.Exists(iniFilePath))
{
File.Create(iniFilePath).Close();
}
}
}
}
+126
View File
@@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{76DE07E0-9E97-44AB-8148-01B44C5C1ADD}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>JY.Utility</RootNamespace>
<AssemblyName>JY.Utility</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\..\JY.Inspection\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="BouncyCastle.Crypto, Version=1.8.9.0, Culture=neutral, PublicKeyToken=0e99375e54769942, processorArchitecture=MSIL">
<HintPath>..\packages\Portable.BouncyCastle.1.8.9\lib\net40\BouncyCastle.Crypto.dll</HintPath>
</Reference>
<Reference Include="CsvHelper, Version=30.0.0.0, Culture=neutral, PublicKeyToken=8c4959082be5c823, processorArchitecture=MSIL">
<HintPath>..\packages\CsvHelper.30.0.1\lib\net47\CsvHelper.dll</HintPath>
</Reference>
<Reference Include="EPPlus, Version=8.0.8.0, Culture=neutral, PublicKeyToken=ea159fdaa78159a1, processorArchitecture=MSIL">
<HintPath>..\packages\EPPlus.8.0.8\lib\net462\EPPlus.dll</HintPath>
</Reference>
<Reference Include="EPPlus.Interfaces, Version=8.0.0.0, Culture=neutral, PublicKeyToken=a694d7f3b0907a61, processorArchitecture=MSIL">
<HintPath>..\packages\EPPlus.Interfaces.8.0.0\lib\net462\EPPlus.Interfaces.dll</HintPath>
</Reference>
<Reference Include="ICSharpCode.SharpZipLib, Version=1.4.2.13, Culture=neutral, PublicKeyToken=1b03e6acf1164f73, processorArchitecture=MSIL">
<HintPath>..\packages\SharpZipLib.1.4.2\lib\netstandard2.0\ICSharpCode.SharpZipLib.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.13\lib\net45\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IO.RecyclableMemoryStream, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.IO.RecyclableMemoryStream.3.0.1\lib\netstandard2.0\Microsoft.IO.RecyclableMemoryStream.dll</HintPath>
</Reference>
<Reference Include="NPOI, Version=2.5.5.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<HintPath>..\packages\NPOI.2.5.5\lib\net45\NPOI.dll</HintPath>
</Reference>
<Reference Include="NPOI.OOXML, Version=2.5.5.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<HintPath>..\packages\NPOI.2.5.5\lib\net45\NPOI.OOXML.dll</HintPath>
</Reference>
<Reference Include="NPOI.OpenXml4Net, Version=2.5.5.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<HintPath>..\packages\NPOI.2.5.5\lib\net45\NPOI.OpenXml4Net.dll</HintPath>
</Reference>
<Reference Include="NPOI.OpenXmlFormats, Version=2.5.5.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<HintPath>..\packages\NPOI.2.5.5\lib\net45\NPOI.OpenXmlFormats.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel.Annotations, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.ComponentModel.Annotations.5.0.0\lib\net461\System.ComponentModel.Annotations.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Security" />
<Reference Include="System.Security.Cryptography.Xml, Version=8.0.0.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Cryptography.Xml.8.0.2\lib\net462\System.Security.Cryptography.Xml.dll</HintPath>
</Reference>
<Reference Include="System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Windows.Forms.DataVisualization" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ChartHelper.cs" />
<Compile Include="ConvertHelper.cs" />
<Compile Include="CSVHelper.cs" />
<Compile Include="CustomAttributeHelper.cs" />
<Compile Include="DataList.cs" />
<Compile Include="EPPlusExcelHelper.cs" />
<Compile Include="ExcelImporter.cs" />
<Compile Include="IniFileHelper.cs" />
<Compile Include="LogHelper.cs" />
<Compile Include="OpenOfficeXML.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TxtHelper.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectView>ProjectFiles</ProjectView>
</PropertyGroup>
</Project>
+389
View File
@@ -0,0 +1,389 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using log4net;
using log4net.Appender;
using log4net.Config;
namespace JY.Utility
{
/// <summary>
/// LogHelper 用来记录系统的日志,包括异常等.
/// </summary>
public static class LogHelper
{
private static readonly ILog log;
/// <summary>
/// </summary>
public static bool DebugMode = false;
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
static LogHelper()
{
var repository = LogManager.CreateRepository("NETCoreRepository");
var c = XmlConfigurator.Configure(repository, new FileInfo("Log4net.config"));
log = LogManager.GetLogger(repository.Name, "Test");
RunClearJob();
}
#endregion
#region 清除过期日志
/// <summary>
/// 启动清除过期日志线程
/// </summary>
private static void RunClearJob()
{
Task.Run(() =>
{
try
{
while (true)
{
ClearOverdue();
WriteLine("清除log4net过期日志");
//24小时清一次
Thread.Sleep(1000 * 60 * 60 * 24);
}
}
catch (Exception e)
{
WriteException(e);
}
});
}
/// <summary>
/// 定期清除过期日志
/// </summary>
private static void ClearOverdue()
{
var days = 7;
if (File.Exists("Log4net.config"))
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(@"Log4net.config");
var node = doc.SelectSingleNode("/configuration/log4net");
days = Convert.ToInt32(node.Attributes["OverdueDays"].Value);
}
catch
{
// ignored
}
}
var apps = log.Logger.Repository.GetAppenders();
if (apps.Length <= 0)
{
return;
}
var now = DateTime.UtcNow.AddDays(-days);
foreach (var item in apps)
{
if (item is RollingFileAppender roll)
{
var dir = Path.GetDirectoryName(roll.File);
var files = Directory.GetFiles(dir, "*.log.*");
//var sample = "log.txt2017-10-23.txt";
foreach (var filePath in files)
{
var file = new FileInfo(filePath);
if (file.CreationTime < now || file.LastWriteTime < now)
{
try
{
file.Delete();
}
catch (Exception)
{
}
}
}
}
}
}
#endregion
#region 公布的写日志函数
/// <summary>
/// 记录一条日志信息。注意:在记录时该程序会自动在左侧增加一格日期。
/// </summary>
/// <param name="strFormat">字符串的组成格式</param>
/// <param name="args">参数</param>
public static void WriteLine(string strFormat, params object[] args)
{
try
{
log.Info($"{string.Format(strFormat, args)}");
}
catch (Exception exp)
{
Trace.WriteLine("LOG ERROR: " + exp.Message);
}
}
/// <summary>
/// 记录一条日志信息。注意:在记录时该程序会自动在左侧增加一格日期。
/// </summary>
/// <param name="strLog">字符串的组成格式</param>
public static void WriteLine(string strLog)
{
try
{
Debug.Assert(strLog != null);
log.Info($"{strLog}");
}
catch (Exception exp)
{
Trace.WriteLine("LOG ERROR: " + exp.Message);
}
}
/// <summary>
/// 记录一条错误日志信息。注意:在记录时该程序会自动在左侧增加一格日期。
/// </summary>
/// <param name="strLog"></param>
public static void WriteErrorLine(string strLog)
{
try
{
Debug.Assert(strLog != null);
log.Error($"{strLog}");
}
catch (Exception exp)
{
Trace.WriteLine("LOG ERROR: " + exp.Message);
}
}
/// <summary>
/// 记录一条日志信息。注意:在记录时该程序会自动在左侧增加一格日期。
/// </summary>
/// <param name="strLog">字符串的组成格式</param>
public static void WriteDebugLine(string strLog)
{
try
{
Debug.Assert(strLog != null);
log.Debug($"{strLog}");
}
catch (Exception exp)
{
Trace.WriteLine("LOG ERROR: " + exp.Message);
}
}
/// <summary>
/// 记录异常(在调试模式)
/// </summary>
/// <param name="exp"></param>
public static void WriteDebugException(Exception exp)
{
WriteDebugException(exp, null);
}
/// <summary>
/// 记录异常(在调试模式)
/// </summary>
/// <param name="exp"></param>
/// <param name="strFormat"></param>
/// <param name="args"></param>
public static void WriteDebugException(Exception exp, string strFormat, params object[] args)
{
try
{
Debug.Assert(exp != null);
var sb = new StringBuilder();
sb.AppendFormat("[{0}] DEBUG 找到 [{1}] 异常: {2}\r\n", DateTime.Now.ToString("HH:mm:ss"),
exp.GetType().Name, exp.Message);
// 附加信息
if (strFormat != null) sb.AppendFormat(" Annex : {0}\r\n", string.Format(strFormat, args));
// 调试信息
sb.AppendFormat(" Source : {0}\r\n", exp.Source);
sb.AppendFormat(" Time : {0}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sb.AppendFormat(" OS/VER : {0} {1}\r\n", Environment.OSVersion.Platform,
Environment.OSVersion.Version);
sb.AppendFormat(" Thread : {0}\r\n", Thread.CurrentThread.Name);
// 栈信息
sb.AppendFormat(" Stack : {0}\r\n", exp.StackTrace);
// 内部异常, 最多5级
var inner = exp.InnerException;
for (var i = 0; i < 5 && inner != null; i++)
{
// 显示内部异常
sb.AppendFormat(" ----- InnerException ---------------------------\r\n");
sb.AppendFormat(" ExceptionType: {0}\r\n", inner.GetType().Name);
sb.AppendFormat(" Message: {0}\r\n", inner.Message);
sb.AppendFormat(" Stack : {0}\r\n", inner.StackTrace);
// 获取异常的内部异常
inner = inner.InnerException;
}
log.Error(sb.ToString());
}
catch (Exception ex)
{
Trace.WriteLine("LOG ERROR: " + ex.Message);
}
}
/// <summary>
/// 记录下该异常
/// </summary>
/// <param name="exp">需要记录的异常对象</param>
public static void WriteException(Exception exp)
{
WriteException(exp, null);
}
/// <summary>
/// 记录下该异常
/// </summary>
/// <param name="exp">异常对象</param>
/// <param name="strFormat">附加信息格式字符串,如果不需要,则该参数为 null</param>
/// <param name="args">参数</param>
public static void WriteException(Exception exp, string strFormat, params object[] args)
{
try
{
Debug.Assert(exp != null);
var sb = new StringBuilder();
{
sb.AppendFormat("[{0}] 找到 [{1}] 异常: {2}\r\n", DateTime.Now.ToString("HH:mm:ss"), exp.GetType().Name,
exp.Message);
// 附加信息
if (strFormat != null) sb.AppendFormat(" Annex : {0}\r\n", string.Format(strFormat, args));
// 调试信息
sb.AppendFormat(" Source : {0}\r\n", exp.Source);
sb.AppendFormat(" Time : {0}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sb.AppendFormat(" OS/VER : {0} {1}\r\n", Environment.OSVersion.Platform,
Environment.OSVersion.Version);
sb.AppendFormat(" Thread : {0}\r\n", Thread.CurrentThread.Name);
// 栈信息
sb.AppendFormat(" Stack : {0}\r\n", exp.StackTrace);
// 内部异常, 最多5级
var inner = exp.InnerException;
for (var i = 0; i < 5 && inner != null; i++)
{
// 显示内部异常
sb.AppendFormat(" ----- InnerException ---------------------------\r\n");
sb.AppendFormat(" ExceptionType: {0}\r\n", inner.GetType().Name);
sb.AppendFormat(" Message: {0}\r\n", inner.Message);
sb.AppendFormat(" Stack : {0}\r\n", inner.StackTrace);
// 获取异常的内部异常
inner = inner.InnerException;
}
log.Error(sb.ToString());
}
}
catch (Exception ex)
{
Trace.WriteLine("LOG ERROR: " + ex.Message);
}
}
/// <summary>
/// Dump 一个对象
/// </summary>
/// <param name="obj"></param>
public static void WriteObject(object obj)
{
try
{
var sb = new StringBuilder();
if (obj == null)
{
sb.AppendLine("-- The object is null\r\n");
}
else
{
sb.AppendFormat("[{0}] {1} has {2} property\r\n",
DateTime.Now, obj.GetType().Name, obj.GetType().GetProperties().Length);
var pis = obj.GetType().GetProperties();
var iMaxLength = 0;
foreach (var pi in pis)
if (pi.CanRead && !pi.IsSpecialName)
iMaxLength = Math.Max(pi.Name.Length, iMaxLength);
foreach (var pi in pis)
if (pi.CanRead && !pi.IsSpecialName)
sb.AppendFormat(" {0} - {1}\r\n", pi.Name.PadRight(iMaxLength, ' '),
pi.GetValue(obj, null));
}
}
catch (Exception exp)
{
Trace.WriteLine("LOG ERROR: " + exp.Message);
}
}
#endregion
/// <summary>
/// 错误日志带异常
/// </summary>
/// <param name="message"></param>
/// <param name="ex"></param>
public static void Error(string message,Exception ex)
{
ILog log = LogManager.GetLogger("Error");
if (log.IsErrorEnabled)
{
log.Error(message,ex);
}
}
// <summary>
/// 错误日志不带异常
/// </summary>
/// <param name="message">错误日志</param>
public static void Error(string message)
{
ILog log = LogManager.GetLogger("Error");
if (log.IsErrorEnabled)
{
log.Error(message);
}
}
}
}
+259
View File
@@ -0,0 +1,259 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using OfficeOpenXml;
namespace JY.Utility
{
public class OpenOfficeXML
{
/// <summary>
/// EPPlusToExcel
/// </summary>
/// <param name="_D">数据集合</param>
/// <param name="strFileName">Excel文件名</param>
public static void Out_CeLiang(List<DataList> _D, string strFileName)
{
using (OfficeOpenXml.ExcelPackage package = new OfficeOpenXml.ExcelPackage(new FileInfo(strFileName)))
{
string TableName = DateTime.Now.ToString("yyyy-MM-dd");
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(TableName);
#region 绘制列头
worksheet.Cells[1, 1].Value = "不良项目";
worksheet.Cells[1, 2].Value = "数量";
//worksheet.Cells[1, 3].Value = "规格3";
//worksheet.Cells[1, 4, 1, 5].Value = "合并单元格";
//worksheet.Cells[1, 4, 1, 5].Merge = true;
#endregion
#region 数据行
int i = 1;
foreach (DataList Item in _D)
{
worksheet.Cells[i + 1, 1].Value = Item.G1;
worksheet.Cells[i + 1, 2].Value = Item.G2;
//worksheet.Cells[i + 1, 3].Value = Item.G3;
//worksheet.Cells[i + 1, 4, i + 1, 5].Value = Item.G4;
//worksheet.Cells[i + 1, 4, i + 1, 5].Merge = true;
i++;
}
#endregion
if (false == System.IO.Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"Excel\"))
System.IO.Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + @"Excel\");
package.Save();
}
}
public static void Out_TimeCeLiang(List<DataList> _D, string strFileName)
{
using (OfficeOpenXml.ExcelPackage package = new OfficeOpenXml.ExcelPackage(new FileInfo(strFileName)))
{
string TableName = DateTime.Now.ToString("yyyy-MM-dd");
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(TableName);
#region 绘制列头
worksheet.Cells[1, 1].Value = "不良项目";
worksheet.Cells[1, 2].Value = "数量";
//worksheet.Cells[1, 3].Value = "规格3";
//worksheet.Cells[1, 4, 1, 5].Value = "合并单元格";
//worksheet.Cells[1, 4, 1, 5].Merge = true;
#endregion
#region 数据行
int i = 1;
foreach (DataList Item in _D)
{
worksheet.Cells[i + 1, 1].Value = Item.G1;
worksheet.Cells[i + 1, 2].Value = Item.G2;
//worksheet.Cells[i + 1, 3].Value = Item.G3;
//worksheet.Cells[i + 1, 4, i + 1, 5].Value = Item.G4;
//worksheet.Cells[i + 1, 4, i + 1, 5].Merge = true;
i++;
}
#endregion
if (false == System.IO.Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"Excel\"))
System.IO.Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + @"Excel\");
package.Save();
}
}
/// <summary>
/// ExportExcel(使用NPOI的方式)
/// </summary>
/// <param name="DT"></param>
public static int ExportExcel(DataTable DT, string selectDate, ref string strErr)
{
strErr = "";
try
{
if (DT == null & DT.Rows.Count <= 0)
{
strErr = "请先查询统计数据后再执行导出操作!";
return 1;
}
string strFilePath = "";
HSSFWorkbook hssfworkbookDown;
string modelExlPath = Application.StartupPath + "\\EmailTemplate\\Model.xls";
if (File.Exists(modelExlPath) == false) //模板不存在
{
strErr = "程序根目录下EmailTemplate文件夹内找不到导出模板文件!";
return 2;
}
using (FileStream file = new FileStream(modelExlPath, FileMode.Open, FileAccess.Read))
{
hssfworkbookDown = new HSSFWorkbook(file);
file.Close();
}
WriterExcel(hssfworkbookDown, 0, DT);
string filename = selectDate + ".xls";
strFilePath = Application.StartupPath + "\\Temp\\TEEnrollmentForm";
if (Directory.Exists(strFilePath) == false)
{
Directory.CreateDirectory(strFilePath);
}
strFilePath = strFilePath + "\\\\" + filename;
FileStream files = new FileStream(strFilePath, FileMode.Create);
hssfworkbookDown.Write(files);
files.Close();
if (File.Exists(strFilePath) == false) //附件生成失败
{
strErr = "生成EXCEL文件失败";
return 3;
}
strErr = strFilePath;
return 4;
}
catch (Exception ex)
{
strErr = ex.Message;
}
return 0;
}
/// <summary>
/// WriterExcel
/// </summary>
/// <param name="hssfworkbookDown"></param>
/// <param name="sheetIndex"></param>
/// <param name="DT"></param>
public static void WriterExcel(HSSFWorkbook hssfworkbookDown, int sheetIndex, DataTable DT)
{
try
{
#region 设置单元格样式
//字体
HSSFFont fontS9 = (HSSFFont)hssfworkbookDown.CreateFont();
fontS9.FontName = "Arial";
fontS9.FontHeightInPoints = 10;
fontS9.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Normal;
//表格
ICellStyle TableS9 = (ICellStyle)hssfworkbookDown.CreateCellStyle();
TableS9.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
TableS9.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
TableS9.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
TableS9.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
TableS9.WrapText = true;
TableS9.SetFont(fontS9);
#endregion
HSSFSheet sheet = (HSSFSheet)hssfworkbookDown.GetSheetAt(sheetIndex);
hssfworkbookDown.SetSheetHidden(sheetIndex, false);
hssfworkbookDown.SetActiveSheet(sheetIndex);
int n = 2; //因为模板有表头,所以从第2行开始写
for (int j = 0; j < DT.Columns.Count; j++)
{
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(j + n);
//string cv = DT.Columns[j].Caption;
//string strDepID = DT.Rows[j]["序号"].ToString().Trim();
//dataRow.CreateCell(0);
//dataRow.Cells[0].SetCellValue(strDepID == "" ? DT.Rows[j]["日期"].ToString() : "");
dataRow.CreateCell(0);
dataRow.Cells[0].SetCellValue(DT.Rows[j]["日期"].ToString());
dataRow.CreateCell(1);
dataRow.Cells[1].SetCellValue(DT.Rows[j]["班次"].ToString());
dataRow.CreateCell(2);
dataRow.Cells[2].SetCellValue(DT.Rows[j]["班别"].ToString());
dataRow.CreateCell(3);
dataRow.Cells[3].SetCellValue(DT.Rows[j]["工单号"].ToString());
dataRow.CreateCell(4);
dataRow.Cells[4].SetCellValue(DT.Rows[j]["客户名称"].ToString());
dataRow.CreateCell(5);
dataRow.Cells[5].SetCellValue(DT.Rows[j]["投入总数"].ToString());
dataRow.CreateCell(6);
dataRow.Cells[6].SetCellValue(DT.Rows[j]["良品总数"].ToString());
dataRow.CreateCell(7);
dataRow.Cells[7].SetCellValue(DT.Rows[j]["不良总数"].ToString());
dataRow.CreateCell(8);
dataRow.Cells[8].SetCellValue(DT.Rows[j]["不良率"].ToString());
dataRow.CreateCell(9);
dataRow.Cells[9].SetCellValue(DT.Rows[j]["质量缺陷"].ToString());
dataRow.CreateCell(10);
dataRow.Cells[10].SetCellValue(DT.Rows[j]["非质量缺陷"].ToString());
dataRow.CreateCell(11);
dataRow.Cells[11].SetCellValue(DT.Rows[j]["其他不良"].ToString());
dataRow.CreateCell(12);
dataRow.Cells[12].SetCellValue(DT.Rows[j]["侧面不良"].ToString());
dataRow.CreateCell(13);
dataRow.Cells[13].SetCellValue(DT.Rows[j]["正极不良"].ToString());
dataRow.CreateCell(14);
dataRow.Cells[14].SetCellValue(DT.Rows[j]["负极不良"].ToString());
dataRow.CreateCell(15);
dataRow.Cells[15].SetCellValue(DT.Rows[j]["重合不良"].ToString());
dataRow.CreateCell(16);
dataRow.Cells[16].SetCellValue(DT.Rows[j]["喷码不良"].ToString());
dataRow.CreateCell(17);
dataRow.Cells[17].SetCellValue(DT.Rows[j]["侧面凹坑鼓包、变形"].ToString());
dataRow.CreateCell(18);
dataRow.Cells[18].SetCellValue(DT.Rows[j]["侧面脏污漏液"].ToString());
dataRow.CreateCell(19);
dataRow.Cells[19].SetCellValue(DT.Rows[j]["侧面凸点、划痕、破皮、膜内异物"].ToString());
dataRow.CreateCell(20);
dataRow.Cells[20].SetCellValue(DT.Rows[j]["正极面垫不良多放、漏放"].ToString());
dataRow.CreateCell(21);
dataRow.Cells[21].SetCellValue(DT.Rows[j]["正极套膜不良含热缩不良、破损、褶皱、面垫翘起"].ToString());
dataRow.CreateCell(22);
dataRow.Cells[22].SetCellValue(DT.Rows[j]["正极套膜脏污"].ToString());
dataRow.CreateCell(23);
dataRow.Cells[23].SetCellValue(DT.Rows[j]["盖帽不良含漏液、盖帽脏污氧化生锈,划痕,变形"].ToString());
dataRow.CreateCell(24);
dataRow.Cells[24].SetCellValue(DT.Rows[j]["负极套膜尺寸不良"].ToString());
dataRow.CreateCell(25);
dataRow.Cells[25].SetCellValue(DT.Rows[j]["负极套膜不良含套膜褶皱变形、破损、褶皱"].ToString());
dataRow.CreateCell(26);
dataRow.Cells[26].SetCellValue(DT.Rows[j]["负极套膜脏污"].ToString());
dataRow.CreateCell(27);
dataRow.Cells[27].SetCellValue(DT.Rows[j]["底部不良含漏液、脏污、氧化生锈、划痕、变形"].ToString());
dataRow.CreateCell(28);
dataRow.Cells[28].SetCellValue(DT.Rows[j]["操作员"].ToString());
//for (int i = 0; i <= 2; i++) //循环列,添加样式
//{
// dataRow.Cells[i].CellStyle = TableS9;
//}
}
//设定第一行,第一列的单元格选中
sheet.SetActiveCell(0, 0);
}
catch (Exception ex)
{
//WriteLog(ex.ToString());
}
}
}
}
+36
View File
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("JY.Utility")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JY.Utility")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("76de07e0-9e97-44ab-8148-01b44c5c1add")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+68
View File
@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace JY.Utility
{
public class TxtHelper
{
static ReaderWriterLockSlim sucessLogWriteLockSlim = new ReaderWriterLockSlim();
/// <summary>
/// 写入TEXT文本
/// </summary>
/// <param name="fullName">文件名</param>
/// <param name="content">内容</param>
/// <returns>保存结果</returns>
public static bool WriteTxt(string fullName, string content)
{
FileStream fs = null;
StreamWriter sw = null;
try
{
string directory = fullName.Substring(0, fullName.LastIndexOf('\\'));
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
sucessLogWriteLockSlim.EnterWriteLock();//加锁防止抢占
if (!File.Exists(fullName))
{
fs = new FileStream(fullName, FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs, Encoding.UTF8);
}
else
{
fs = new FileStream(fullName, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs, Encoding.UTF8);
}
sw.WriteLine(content);
sw.Close();
fs.Close();
return true;
}
catch (Exception ex)
{
sw?.Close();
fs?.Close();
}
finally
{
sucessLogWriteLockSlim.ExitWriteLock();
}
return false;
}
}
}
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.4.1" newVersion="4.0.4.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="ICSharpCode.SharpZipLib" publicKeyToken="1b03e6acf1164f73" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.4.2.13" newVersion="1.4.2.13" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" /></startup></configuration>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="CsvHelper" version="30.0.1" targetFramework="net48" />
<package id="EPPlus" version="8.0.8" targetFramework="net48" />
<package id="EPPlus.Interfaces" version="8.0.0" targetFramework="net48" />
<package id="log4net" version="2.0.13" targetFramework="net472" />
<package id="Microsoft.Bcl.AsyncInterfaces" version="1.0.0" targetFramework="net472" />
<package id="Microsoft.Bcl.HashCode" version="1.0.0" targetFramework="net472" />
<package id="Microsoft.CSharp" version="4.3.0" targetFramework="net472" />
<package id="Microsoft.IO.RecyclableMemoryStream" version="3.0.1" targetFramework="net48" />
<package id="NPOI" version="2.5.5" targetFramework="net452" />
<package id="Portable.BouncyCastle" version="1.8.9" targetFramework="net452" />
<package id="SharpZipLib" version="1.4.2" targetFramework="net48" />
<package id="System.Buffers" version="4.5.1" targetFramework="net48" />
<package id="System.ComponentModel.Annotations" version="5.0.0" targetFramework="net48" />
<package id="System.Memory" version="4.5.5" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="4.5.3" targetFramework="net48" />
<package id="System.Security.Cryptography.Xml" version="8.0.2" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.2" targetFramework="net472" />
<package id="System.ValueTuple" version="4.3.0" targetFramework="net452" />
</packages>