using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Linq; using System.Reflection; using System.Web; using MESClassLibrary.BLL.Log; using MESWebSite.CommonClass; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; namespace MESWebSite.Tool { public class ExcelTool { /// /// 导出Excel /// /// 导出的数据集合类型 /// 导出的数据集合 /// 导出的Excel实体类型 /// public XSSFWorkbook Export(List data, Type type) where T : class { XSSFWorkbook book = new XSSFWorkbook(); ISheet sheet = book.CreateSheet("Sheet1"); IRow hrow = sheet.CreateRow(0); PropertyInfo[] prop = type.GetProperties(); // 通过反射写入表头 WriteHeader(hrow, prop); // 通国反射写入内容 WriteContent(sheet, data, prop); return book; } public void WriteHeader(IRow row, PropertyInfo[] header) { for (int i = 0; i < header.Length; i++) { ICell cell = row.CreateCell(i); var col = header[i]; ExportHeaderAttribute attr = col.GetCustomAttribute(); if (attr == null) { cell.SetCellValue(col.Name); } else { cell.SetCellValue(attr.HeaderName); } } } public void WriteContent(ISheet sheet, List data, PropertyInfo[] header) { for (int i = 0; i < data.Count; i++) { IRow row = sheet.CreateRow(i + 1); for (int j = 0; j < header.Length; j++) { ICell cell = row.CreateCell(j); T o = data[i]; var prop = o.GetType().GetProperty(header[j].Name); if (prop != null) { cell.SetCellValue(prop.GetValue(o).ToString()); } } } } public static DataTable GetExcelTableByOleDB(string strExcelPath, string tableName) { OleDbConnection objConn = null; try { DataTable dtExcel = new DataTable(); //数据表 DataSet ds = new DataSet(); //获取文件扩展名 string strExtension = System.IO.Path.GetExtension(strExcelPath); string strFileName = System.IO.Path.GetFileName(strExcelPath); //Excel的连接 switch (strExtension) { case ".xls": objConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strExcelPath + ";" + "Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;\""); break; case ".xlsx": objConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelPath + ";" + "Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1;\""); break; default: objConn = null; break; } if (objConn == null) { return null; } try { objConn.Open(); } catch (Exception ex) { } //获取Excel中所有Sheet表的信息 //System.Data.DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null); //获取Excel的第一个Sheet表名 //string tableName = schemaTable.Rows[0][2].ToString().Trim(); string strSql = "select * from [" + tableName + "$]"; //获取Excel指定Sheet表中的信息 OleDbCommand objCmd = new OleDbCommand(strSql, objConn); OleDbDataAdapter myData = new OleDbDataAdapter(strSql, objConn); myData.Fill(ds, tableName);//填充数据 objConn.Close(); //dtExcel即为excel文件中指定表中存储的信息 dtExcel = ds.Tables[tableName]; return dtExcel; } catch (Exception ex) { if (objConn != null) { objConn.Close(); } LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod()); return null; } } } }