Excel數據導入導出
阿新 • • 發佈:2019-03-12
points 頁眉 font width pep objects 單元 開始 system
註釋: 使用Window自帶的 Microsoft.Office.Interop.Excel; 類庫實現
具體代碼如下:
/// <summary> /// 導出Excel類 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="U"></typeparam> /// public class ImportFromExcel<T, U> where T : class, new() where U : ListView Code<T>, new() /// public class ExportToExcel<T, U> where T : class where U : List<T> public class ExcelHelper<T, U> where T : class, new() where U : List<T>, new() { #region 對象數據 導出為Excel /// <summary> /// 數據集 /// </summary>public List<T> LstTMdl { get; set; } // 可選 參數 private object _missingValue = Missing.Value; /// <summary> /// 生成Excel報表 /// </summary> /// <param name="excelFullName">Excel全路徑</param> /// <returns></returns>public bool ExportObjectsToExcel(string excelFullName) { bool isSuccess = false; Application excelApp = null; //Microsoft.Office.Interop.Excel.Application Workbooks books = null; _Workbook book = null; Sheets sheets = null; _Worksheet workSheet = null; try { if (LstTMdl != null) { // 創建 Excel 傳遞的參數實例 excelApp = new Application(); excelApp.DisplayAlerts = false; //保存Excel的時候,不彈出是否保存的窗口直接進行保存 books = excelApp.Workbooks; book = books.Add(_missingValue); sheets = book.Worksheets; workSheet = (_Worksheet)(sheets.get_Item(1)); //Excel sheet 索引從1開始 // 存在數據則輸出(填充 Excel sheet) if (LstTMdl.Count != 0) { //根據屬性名創建列標題 PropertyInfo[] propertyInfo = typeof(T).GetProperties(); // 為標頭創建Array object[] arrExcelFileds = GetExcelFiledsName(propertyInfo); //開始從 A1 處添加 AddExcelRows(workSheet, "A1", 1, arrExcelFileds.Length, arrExcelFileds); //將數據寫入 Excel sheet object[,] cellsContent = GetExcelCellsContent(arrExcelFileds); AddExcelRows(workSheet, "A2", LstTMdl.Count, arrExcelFileds.Length, cellsContent); // 根據數據擬合列 AutoFitColumns(workSheet, "A1", LstTMdl.Count + 1, arrExcelFileds.Length); } //excelApp.Visible = true;//展示 Excel 程序 book.SaveAs(excelFullName);//直接保存Excel文件(不打開) isSuccess = true; } book.Close(); excelApp.Quit(); } catch (Exception ex) { isSuccess = false; } finally { ReleaseObject(workSheet); ReleaseObject(sheets); ReleaseObject(book); ReleaseObject(books); ReleaseObject(excelApp); } return isSuccess; } /// <summary> /// 獲取Excel各單元格內容 /// </summary> /// <param name="arrExcelFileds"></param> /// <returns></returns> private object[,] GetExcelCellsContent(object[] arrExcelFileds) { object[,] cellsContent = new object[LstTMdl.Count, arrExcelFileds.Length]; for (int j = 0; j < LstTMdl.Count; j++) { var item = LstTMdl[j]; for (int i = 0; i < arrExcelFileds.Length; i++) { var y = typeof(T).InvokeMember(arrExcelFileds[i].ToString(), BindingFlags.GetProperty, null, item, null); cellsContent[j, i] = (y == null) ? "" : y.ToString(); } } return cellsContent; } /// <summary> /// 獲取Excel列頭名稱 /// </summary> /// <param name="propertyInfo"></param> /// <returns></returns> private object[] GetExcelFiledsName(PropertyInfo[] propertyInfo) { List<object> objHeaders = new List<object>(); for (int n = 0; n < propertyInfo.Length; n++) { objHeaders.Add(propertyInfo[n].Name); } var arrExcelFileds = objHeaders.ToArray(); return arrExcelFileds; } /// <summary> /// 添加行數據 /// </summary> /// <param name="startCell"></param> /// <param name="rowCount"></param> /// <param name="colCount"></param> /// <param name="values"></param> /// <param name="numberFormatLocal">默認值 "@" :單元格格式為文本</param> private void AddExcelRows(_Worksheet workSheet, string startCell, int rowCount, int colCount, object values, string numberFormatLocal, bool isFontBold = false) { Range range = workSheet.get_Range(startCell, _missingValue); range = range.get_Resize(rowCount, colCount); range.Columns.AutoFit(); // 設置列寬為自動適應 range.NumberFormatLocal = numberFormatLocal; //設置單元格格式. "@":為文本 Font font = range.Font; font.Bold = isFontBold; range.set_Value(_missingValue, values); } /// <summary> /// 添加行數據 /// </summary> /// <param name="startCell"></param> /// <param name="rowCount"></param> /// <param name="colCount"></param> /// <param name="values"></param> private void AddExcelRows(_Worksheet workSheet, string startCell, int rowCount, int colCount, object values) { AddExcelRows(workSheet, startCell, rowCount, colCount, values, "@"); } /// <summary> /// 添加行數據 /// </summary> /// <param name="startCell"></param> /// <param name="rowCount"></param> /// <param name="colCount"></param> /// <param name="values"></param> private void AddExcelFiledTitles(_Worksheet workSheet, string startCell, int rowCount, int colCount, object values) { // 列標題設置為加粗字體 AddExcelRows(workSheet, startCell, rowCount, colCount, values, "@", true); } /// <summary> /// 根據數據擬合列 /// </summary> /// <param name="startCell"></param> /// <param name="rowCount"></param> /// <param name="colCount"></param> private void AutoFitColumns(_Worksheet workSheet, string startCell, int rowCount, int colCount) { Range range = workSheet.get_Range(startCell, _missingValue); range = range.get_Resize(rowCount, colCount); range.Columns.AutoFit(); } #endregion #region 讀取Excel文件內數據 為對象 ///// <summary> ///// 導出Excel類 ///// </summary> ///// <typeparam name="T"></typeparam> ///// <typeparam name="U"></typeparam> //public class ImportFromExcel<T, U> where T : class, new() where U : List<T>, new() //{ /// <summary> /// 讀Excel表內容 /// </summary> /// <returns></returns> public U ReadExcelData(string excelFullName) { U lstData = new U(); Application excelApp = new Application(); //excelApp.Visible = false; //excelApp.UserControl = true; _Workbook book = excelApp.Application.Workbooks.Open(excelFullName); _Worksheet sheet = (_Worksheet)(book.Worksheets.get_Item(1)); try { int rowsCount = sheet.UsedRange.Rows.Count; // sheet.UsedRange.Cells.Rows.Count;//行數 int columnsCount = sheet.UsedRange.Columns.Count; // sheet.UsedRange.Cells.Columns.Count; //列數 //列頭 PropertyInfo[] headerInfo = typeof(T).GetProperties(); Dictionary<PropertyInfo, int> keyValuePairs = new Dictionary<PropertyInfo, int>(); for (int i = 1; i <= columnsCount; i++) { var value = sheet.Cells[1, i].Value2.ToString(); //取單元格值 var propertyInfo = headerInfo.Where(pInfo => pInfo.Name == value).FirstOrDefault(); if (propertyInfo != null) { keyValuePairs.Add(propertyInfo, i); } } //內容 for (int j = 2; j <= rowsCount; j++) { T instance = new T(); foreach (var keyValue in keyValuePairs) { var propertyInfo = keyValue.Key; var propertyValue = sheet.Cells[j, keyValue.Value].Value2.ToString(); //取單元格值 ReflectionHelper.SetInstancePropertyValue(instance, propertyInfo, propertyValue); } lstData.Add(instance); } } catch (Exception ex) { lstData = null; //LogHelper.Instance.Error("" + ex.ToString()); } finally { book?.Close(); excelApp?.Quit(); ReleaseObject(sheet); ReleaseObject(book); ReleaseObject(excelApp); } return lstData; } //} #endregion #region 公共 /// <summary> /// 釋放未使用的對象 /// </summary> /// <param name="obj"></param> private void ReleaseObject(object obj) { try { if (obj != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } } catch (Exception ex) { obj = null; } finally { GC.Collect(); } } #endregion }
參考:
#region 參考 /************************ * * range.NumberFormatLocal = "@"; //設置單元格格式為文本 range = (Range)worksheet.get_Range("A1", "E1"); //獲取Excel多個單元格區域:本例做為Excel表頭 range.Merge(0); //單元格合並動作 worksheet.Cells[1, 1] = "Excel單元格賦值"; //Excel單元格賦值 range.Font.Size = 15; //設置字體大小 range.Font.Underline=true; //設置字體是否有下劃線 range.Font.Name="黑體"; 設置字體的種類 range.HorizontalAlignment=XlHAlign.xlHAlignCenter; //設置字體在單元格內的對其方式 range.ColumnWidth=15; //設置單元格的寬度 range.Cells.Interior.Color=System.Drawing.Color.FromArgb(255,204,153).ToArgb(); //設置單元格的背景色 range.Borders.LineStyle=1; //設置單元格邊框的粗細 range.BorderAround(XlLineStyle.xlContinuous,XlBorderWeight.xlThick,XlColorIndex.xlColorIndexAutomatic,System.Drawing.Color.Black.ToArgb()); //給單元格加邊框 range.Borders.get_Item(Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop).LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone; //設置單元格上邊框為無邊框 range.EntireColumn.AutoFit(); //自動調整列寬 Range.HorizontalAlignment= xlCenter; // 文本水平居中方式 Range.VerticalAlignment= xlCenter //文本垂直居中方式 Range.WrapText=true; //文本自動換行 Range.Interior.ColorIndex=39; //填充顏色為淡紫色 Range.Font.Color=clBlue; //字體顏色 xlsApp.DisplayAlerts=false; //保存Excel的時候,不彈出是否保存的窗口直接進行保存 ==================================================================== using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.Office.Interop.Excel; using ExcelApplication = Microsoft.Office.Interop.Excel.ApplicationClass; using System.IO; namespace ExcalDemo { public class ExcelFiles { public void CreateExcelFiles() { ExcelApplication excel = new ExcelApplication(); try { excel.Visible = false;// 不顯示 Excel 文件,如果為 true 則顯示 Excel 文件 excel.Workbooks.Add(Missing.Value);// 添加工作簿 Worksheet sheet = (Worksheet)excel.ActiveSheet;// 獲取當前工作表 Range range = null;// 創建一個空的單元格對象 range = sheet.get_Range("A1", Missing.Value);// 獲取單個單元格 range.RowHeight = 20; // 設置行高 range.ColumnWidth = 20; // 設置列寬 range.Borders.LineStyle = 1; // 設置單元格邊框 range.Font.Bold = true; // 加粗字體 range.Font.Size = 20; // 設置字體大小 range.Font.ColorIndex = 5; // 設置字體顏色 range.Interior.ColorIndex = 6; // 設置單元格背景色 range.HorizontalAlignment = XlHAlign.xlHAlignCenter;// 設置單元格水平居中 range.VerticalAlignment = XlVAlign.xlVAlignCenter;// 設置單元格垂直居中 range.Value2 = "設置行高和列寬";// 設置單元格的值 range = sheet.get_Range("B2", "D4");// 獲取多個單元格 range.Merge(Missing.Value); // 合並單元格 range.Columns.AutoFit(); // 設置列寬為自動適應 range.NumberFormatLocal = "#,##0.00";// 設置單元格格式為貨幣格式 // 設置單元格左邊框加粗 range.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick; // 設置單元格右邊框加粗 range.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick; range.Value2 = "合並單元格"; // 頁面設置 sheet.PageSetup.PaperSize = XlPaperSize.xlPaperA4; // 設置頁面大小為A4 sheet.PageSetup.Orientation = XlPageOrientation.xlPortrait; // 設置垂直版面 sheet.PageSetup.HeaderMargin = 0.0; // 設置頁眉邊距 sheet.PageSetup.FooterMargin = 0.0; // 設置頁腳邊距 sheet.PageSetup.LeftMargin = excel.InchesToPoints(0.354330708661417); // 設置左邊距 sheet.PageSetup.RightMargin = excel.InchesToPoints(0.354330708661417);// 設置右邊距 sheet.PageSetup.TopMargin = excel.InchesToPoints(0.393700787401575); // 設置上邊距 sheet.PageSetup.BottomMargin = excel.InchesToPoints(0.393700787401575);// 設置下邊距 sheet.PageSetup.CenterHorizontally = true; // 設置水平居中 // 打印文件 sheet.PrintOut(Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); // 保存文件到程序運行目錄下 sheet.SaveAs(Path.Combine(System.Windows.Forms.Application.StartupPath,"demo.xls"), Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); excel.ActiveWorkbook.Close(false, null, null); // 關閉 Excel 文件且不保存 } catch (Exception ex) { MessageBox.Show(this,ex.Message); } finally { excel.Quit(); // 退出 Excel excel = null; // 將 Excel 實例設置為空 } } } } * * *********************************/ #endregionView Code
Excel數據導入導出