领胜LDS 键盘AOI检测项目
wells.liu
2020-07-09 6caa156ba8be9728b4cb67c7c7be326b0316f773
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
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
 
namespace Bro.M071.DBManager
{
 
    public class ExcelExportSet
    {
        public List<string> Worksheets { get; set; }
 
        /// <summary>
        /// Key: Worksheet的名称 Value:Worksheet对应的列名集合(key 为要导出的列名 value 为导出后显示的列名)
        /// </summary>
        public Dictionary<string, Dictionary<string, string>> WorksheetColumns { get; set; }
        public Dictionary<string, DataTable> WorksheetDataTable { get; set; }
 
    }
 
    /// <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)
        {
            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;  //开始的行
                                                                                 //是否显示行编号
                    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);
                    // autofit width of cells with small content 
                    int columnIndex = 1;
                    foreach (DataColumn item in dataTable.Columns)
                    {
                        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();
                        }
                        columnIndex++;
                    }
                    // 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);
                    }
                    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>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="data"></param>
        ///// <param name="heading"></param>
        ///// <param name="isShowSlNo"></param>
        ///// <param name="columnsToTake"></param>
        ///// <returns></returns>
        //public static byte[] ExportExcel<T>(List<T> data, string heading = "", bool isShowSlNo = false, params string[] columnsToTake)
        //{
        //    ExcelExportSet excelExport = new ExcelExportSet();
        //    excelExport.
        //    return ExportExcel(ListToDataTable(data), heading, isShowSlNo, columnsToTake);
        //}
    }
}