领胜LDS 键盘AOI检测项目
xcd
2020-07-15 d3a44f202c0b12cbac67c71129c3c4f480df55b9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
 
namespace Bro.M071.DBManager
{
 
    public class ExcelExportSet
    {
        public List<string> Worksheets { get; set; } = new List<string>();
 
        /// <summary>
        /// Key: Worksheet的名称 Value:Worksheet对应的列名集合(key 为要导出的列名 value 为导出后显示的列名)
        /// </summary>
        public Dictionary<string, Dictionary<string, string>> WorksheetColumns { get; set; } = new Dictionary<string, Dictionary<string, string>>();
 
        public Dictionary<string, Dictionary<string, string>> WorksheetRows { get; set; } = new Dictionary<string, Dictionary<string, string>>();
 
        public Dictionary<string, DataTable> WorksheetDataTable { get; set; } = new Dictionary<string, DataTable>();
 
        //public ExcelExportSet()
        //{
        //    Worksheets = new List<string>();
        //    WorksheetColumns = new Dictionary<string, Dictionary<string, string>>();
        //    WorksheetDataTable = new Dictionary<string, DataTable>();
        //}
 
    }
 
    /// <summary>
    /// Excel导出帮助类
    /// </summary>
    public class ExcelExportHelper
    {
        public static string ExcelContentType => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        /// <summary>
        /// List转DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(List<T> data, Dictionary<string, string> worksheetColumns)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dataTable = new DataTable();
            Dictionary<string, string> tempColumns = new Dictionary<string, string>();
            foreach (var column in worksheetColumns)
            {
                PropertyDescriptor property = properties.Find(column.Key, true);
                if (property != null)
                {
                    dataTable.Columns.Add(column.Value, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
                    tempColumns[column.Key] = column.Value;
                }
            }
            object[] values = new object[tempColumns.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < tempColumns.Count; i++)
                {
                    PropertyDescriptor property = properties.Find(tempColumns.ElementAt(i).Key, true);
                    values[i] = property.GetValue(item);
                }
                dataTable.Rows.Add(values);
            }
            return dataTable;
        }
 
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="dataTable">数据源</param>
        /// <param name="worksheet">工作簿Worksheet</param>
        /// <param name="showSrNo">//是否显示行编号</param>
        /// <param name="columnsToTake">要导出的列</param>
        /// <returns></returns>
        public static byte[] ExportExcel(ExcelExportSet excelExportDto, bool showSrNo = false)
        {
            //ExcelPackage.LicenseContext = LicenseContext.Commercial; 5.0以上版本 需要授权
            byte[] result = null;
            using (ExcelPackage package = new ExcelPackage())
            {
                foreach (var worksheet in excelExportDto.Worksheets)
                {
                    var dataTable = excelExportDto.WorksheetDataTable[worksheet];
                    ExcelWorksheet workSheet = package.Workbook.Worksheets.Add($"{worksheet}");
                    //int startRowFrom = string.IsNullOrEmpty(worksheet) ? 1 : 3;  //开始的行
                    int startRowFrom = 1;  //开始的行
                                           //是否显示行编号
                    if (showSrNo)
                    {
                        DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
                        dataColumn.SetOrdinal(0);
                        int index = 1;
                        foreach (DataRow item in dataTable.Rows)
                        {
                            item[0] = index;
                            index++;
                        }
                    }
                    //Add Content Into the Excel File
                    workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
 
                    for (int columnIndex = 1; columnIndex <= dataTable.Columns.Count; columnIndex++)
                    {
                        // autofit width of cells with small content 
                        ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
                        int maxLength = columnCells.Max(cell => (cell.Value ?? "").ToString().Count());
                        if (maxLength < 150)
                        {
                            workSheet.Column(columnIndex).AutoFit();
                        }
                        // 设置NG单元格样式
                        for (int rowIndex = 1; rowIndex <= dataTable.Rows.Count; rowIndex++)
                        {
                            if (columnCells[rowIndex, columnIndex].Text == "NG")
                            {
                                workSheet.Cells[rowIndex, columnIndex].Style.Font.Bold = true;//字体为粗体
                                workSheet.Cells[rowIndex, columnIndex].Style.Fill.PatternType = ExcelFillStyle.Solid;
                                workSheet.Cells[rowIndex, columnIndex].Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#E33E33"));// 设置填充样式
                            }
                        }
                    }
                    // format header - bold, yellow on black 设置表头样式
                    using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
                    {
                        r.Style.Font.Color.SetColor(System.Drawing.Color.White);
                        r.Style.Font.Bold = true;
                        r.Style.Fill.PatternType = ExcelFillStyle.Solid;
                        r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb5ad"));
                    }
                    // format cells - add borders 
                    using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
                    {
                        r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                        r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                        r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                        r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
                        r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
                        r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
                        r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
                        r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
                    }
                    //将sheet写入表中
                    //if (!string.IsNullOrEmpty(worksheet))
                    //{
                    //    workSheet.Cells["A1"].Value = worksheet;
                    //    workSheet.Cells["A1"].Style.Font.Size = 20;
                    //    workSheet.InsertColumn(1, 1);
                    //    workSheet.InsertRow(1, 1);
                    //    workSheet.Column(1).Width = 5;
                    //}
                }
                result = package.GetAsByteArray();
            }
            return result;
        }
 
        /// <summary>
        /// 新建 或 追加 写入Excel
        /// </summary>
        /// <param name="excelExportDto"></param>
        /// <param name="fileName">要写入的文件名(全路径名)</param>
        /// <param name="showSrNo"></param>
        /// <returns></returns>
        public static byte[] CreateOrAppendExcel(ExcelExportSet excelExportDto, string fileName, bool showSrNo = false)
        {
            byte[] result = null;
            bool isExist = File.Exists(fileName);
            ExcelExportSet newExcelSet = new ExcelExportSet();
 
            if (isExist)
            {
                var oldWorksheetDataTable = WorksheetToTable(fileName, excelExportDto.Worksheets);
                newExcelSet.Worksheets = excelExportDto.Worksheets;
                newExcelSet.WorksheetColumns = excelExportDto.WorksheetColumns;
 
                foreach (var sheet in excelExportDto.Worksheets)
                {
                    var oldTable = oldWorksheetDataTable[sheet];
                    newExcelSet.WorksheetDataTable[sheet] = oldTable;
                    if (excelExportDto.WorksheetDataTable[sheet].Rows.Count > 0)
                    {
                        //合并两个 datatable
                        newExcelSet.WorksheetDataTable[sheet].Merge(excelExportDto.WorksheetDataTable[sheet]);
                    }
                }
            }
            else
            {
                newExcelSet = excelExportDto;
            }
 
            result = ExportExcel(newExcelSet, showSrNo);
            return result;
        }
 
        /// <summary>
        ///将指定的Excel的文件转换成DataTable (Excel的指定sheet)
        /// </summary>
        /// <param name="fullFielPath">文件的绝对路径</param>
        /// <returns></returns>
        public static Dictionary<string, DataTable> WorksheetToTable(string fullFielPath, List<string> worksheets)
        {
            try
            {
                var resultWorksheetDataTable = new Dictionary<string, DataTable>();
                FileInfo existingFile = new FileInfo(fullFielPath);
                ExcelPackage package = new ExcelPackage(existingFile);
                foreach (var sheet in worksheets)
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[sheet];//选定 指定页
                    var dataTable = WorksheetToTable(worksheet);
                    resultWorksheetDataTable[sheet] = dataTable;
                }
                return resultWorksheetDataTable;
            }
            catch (Exception)
            {
                throw;
            }
        }
 
        /// <summary>
        /// 将worksheet转成datatable
        /// </summary>
        /// <param name="worksheet">待处理的worksheet</param>
        /// <returns>返回处理后的datatable</returns>
        public static DataTable WorksheetToTable(ExcelWorksheet worksheet)
        {
            //获取worksheet的行数
            int rows = worksheet.Dimension.End.Row;
            //获取worksheet的列数
            int cols = worksheet.Dimension.End.Column;
 
            DataTable dt = new DataTable(worksheet.Name);
            DataRow dr = null;
            for (int i = 1; i <= rows; i++)
            {
                if (i > 1)
                    dr = dt.Rows.Add();
 
                for (int j = 1; j <= cols; j++)
                {
                    //默认将第一行设置为datatable的标题
                    if (i == 1)
                        dt.Columns.Add(GetString(worksheet.Cells[i, j].Value));
                    //剩下的写入datatable
                    else
                        dr[j - 1] = GetString(worksheet.Cells[i, j].Value);
                }
            }
            return dt;
        }
        private static string GetString(object obj)
        {
            try
            {
                return (obj ?? "").ToString();
            }
            catch (Exception)
            {
                return "";
            }
        }
    }
 
    
}