泛型列表導出Excel:
最近好多導出問題就整這么個玩意共享給大家public class Export{/// <summary>/// 泛型導出Excel/// </summary>/// <param name="strCaption">Excel文件中的標題</param>/// <param name="pList">泛型列表(最好是同一類型)</param>/// <param name="saveFileDialog">保存文件對話框</param>/// <param name="fileName">要保存的文件名</param>/// <returns>0:成功;1:DataGridView中無記錄;2:Excel無法啟動;9999:異常錯誤</returns>public int ExportExcel(string strCaption, List<object> pList, SaveFileDialog saveFileDialog, string fileName){int result = 9999;//保存saveFileDialog.Filter = "Execl files (*.xls)|*.xls";saveFileDialog.FilterIndex = 0;saveFileDialog.RestoreDirectory = true;saveFileDialog.Title = "導出Excel文件";saveFileDialog.FileName = fileName;int RowCount = pList.Count;if (RowCount <= 0){result = 1;}else{if (saveFileDialog.ShowDialog() == DialogResult.OK){if (saveFileDialog.FileName == string.Empty){MessageBox.Show("請輸入保存文件名!");saveFileDialog.ShowDialog();}Type type = pList[0].GetType();System.Reflection.PropertyInfo[] pis = type.GetProperties();int ColCount = pis.Length;// 創建Excel對象Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();if (xlApp == null){result = 2;}else{try{// 創建Excel工作薄Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];// 設置標題Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); //標題所占的單元格數與DataGridView中的列數相同range.MergeCells = true;xlApp.ActiveCell.FormulaR1C1 = strCaption;xlApp.ActiveCell.Font.Size = 20;xlApp.ActiveCell.Font.Bold = true;xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;// 創建緩存數據object[,] objData = new object[RowCount + 1, ColCount];try{//獲取列標題for (int i = 0; i < pis.Length; i++){objData[0, i] = pis[i].Name;}// 獲取數據for (int i = 1; i <= pList.Count; i++){for (int j = 0; j < pis.Length; j++){objData[i, j] = pis[j].GetValue(pList[i - 1], null);}}}catch{result = 9999;}// 寫入Excelrange = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount + 2, ColCount]);range.Value2 = objData;xlBook.Saved = true;xlBook.SaveCopyAs(saveFileDialog.FileName);}catch (Exception err){result = 9999;}finally{xlApp.Quit();GC.Collect(); //強制回收}//返回值result = 0;}}}return result;}}
?