ExcelHelper

        public static bool ListToExcel<T>(List<T> list, string filePath, bool isShowExcle = true)
        {
            int rowCount = list.Count;
            //int columnCount = new T().GetType().GetMembers().Length;
            if (rowCount == 0)
            {
                return false;
            }
            //建立Excel对象 
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook workBook = excel.Application.Workbooks.Add(true);
            excel.Visible = false;//是否打开该Excel文件 
            excel.Cells.ColumnWidth = 16;//设置单元格宽
            excel.Cells.NumberFormatLocal = "@";//设置所有单元格式

            int colHead = 0;
            foreach (var mi in typeof(T).GetMembers())
            {
                if (mi.MemberType == MemberTypes.Field)
                {
                    colHead++;
                    excel.Cells[1, colHead] = mi.Name;
                }
            }


            int row = 1;
            foreach (var model in list)
            {
                row++;
                int col = 0;
                foreach (var mi in model.GetType().GetMembers())
                {
                    if (mi.MemberType == MemberTypes.Field)
                    {
                        col++;
                        excel.Cells[row, col] = (mi as FieldInfo).GetValue(model);
                    }
                }
            }

            workBook.SaveAs(filePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            try
            {
                workBook.Saved = true;
                excel.UserControl = false;
            }
            catch (Exception ex)
            {
                Log.Writer(ex, "ListToExcel异常");
                return false;
            }
            finally
            {
                workBook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, Missing.Value, Missing.Value);
                excel.Quit();
            }

            if (isShowExcle)
            {
                System.Diagnostics.Process.Start(filePath);
            }
            return true;
        }
        public static DataSet ExcelToDT(string path, bool addNo = true, string sheetName = "sheet1$")
        {
            try
            {
                //string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + "Extended Properties=Excel 8.0;";
                string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + path + ";Extended Properties='Excel 12.0; HDR=YES; IMEX=1'";
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                string strExcel = string.Format("select * from [{0}]", sheetName);
                DataSet ds = new DataSet();
                if (addNo)
                {
                    DataTable dt = new DataTable();
                    dt.TableName = "table1";
                    dt.Columns.Add("SerialNo");
                    ds.Tables.Add(dt);
                }
                OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
                adapter.Fill(ds, "table1");
                if (addNo)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        ds.Tables[0].Rows[i]["SerialNo"] = i + 1;
                    }
                }
                return ds;
            }
            catch (Exception e)
            {
                throw e;
            }

        }
        //只支持属性
        public static List<T> ExcelToT<T>(string path, bool addNo = true, string sheetName = "sheet1$") where T : class, new()
        {
            try
            {
                var ds = ExcelToDT(path, addNo, sheetName);
                if (ds == null)
                {
                    return null;
                }
                List<T> listResult = new List<T>();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    T m = new T();
                    foreach (DataColumn col in ds.Tables[0].Columns)
                    {
                        var p = m.GetType().GetProperties().FirstOrDefault(pi => pi.Name.Equals(col.ColumnName));
                        if (p != null)
                            p.SetValue(m, dr[col], null);
                        //var fieldInfo = m.GetType().GetFields().FirstOrDefault(mi => mi.Name == col.ColumnName && mi.MemberType == MemberTypes.Field);
                        //if (fieldInfo != null)
                        //    fieldInfo.SetValue(m, Convert.ToString(dr[col]));
                    }
                    listResult.Add(m);
                }
                return listResult;
            }
            catch (Exception e)
            {
                throw e;
            }

        }
原文地址:https://www.cnblogs.com/lee2011/p/6728171.html