泛型列表导出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; } // 写入Excel range = 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; } }