日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

导出Excel神器最终版

發布時間:2023/12/13 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 导出Excel神器最终版 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

泛型列表導出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;}}

?

轉載于:https://www.cnblogs.com/haoqi/p/3388213.html

總結

以上是生活随笔為你收集整理的导出Excel神器最终版的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。