文章出自深圳-淘神網友提供方案,在此僅做記錄,謝謝。
public static class ViewExport { /// <summary> /// DevExpress通用匯出Excel,支援多個控制項同時匯出在同一個Sheet表 /// eg:ExportToXlsx("",gridControl1,gridControl2); /// 將gridControl1和gridControl2的資料一同匯出到同一張工作表 /// </summary> /// <param name="title">檔案名稱</param> /// <param name="panels">控制項集</param> public static void ExportToExcel ( string title ,params IPrintable [ ] panels ) { SaveFileDialog saveFileDialog = new SaveFileDialog ( ); saveFileDialog . FileName = title; saveFileDialog . Title = "匯出Excel"; saveFileDialog . Filter = "Excel檔案(*.xlsx)|*.xlsx|Excel檔案(*.xls)|*.xls"; DialogResult dialogResult = saveFileDialog . ShowDialog ( ); if ( dialogResult == DialogResult . Cancel ) return; string FileName = saveFileDialog . FileName; PrintingSystem ps = new PrintingSystem ( ); CompositeLink link = new CompositeLink ( ps ); ps . Links . Add ( link ); foreach ( IPrintable panel in panels ) { link . Links . Add ( CreatePrintableLink ( panel ) ); } link . Landscape = true;//橫向 //判斷是否有標題,有則設定 //link.CreateDocument(); //建立文檔 try { int count = 1; //在重複名稱後加(序號) while ( File . Exists ( FileName ) ) { if ( FileName . Contains ( ")." ) ) { int start = FileName . LastIndexOf ( "(" ); int end = FileName . LastIndexOf ( ")." ) - FileName . LastIndexOf ( "(" ) + 2; FileName = FileName . Replace ( FileName . Substring ( start ,end ) ,string . Format ( "({0})." ,count ) ); } else { FileName = FileName . Replace ( "." ,string . Format ( "({0})." ,count ) ); } count++; } if ( FileName . LastIndexOf ( ".xlsx" ) >= FileName . Length - 5 ) { XlsxExportOptions options = new XlsxExportOptions ( ); link . ExportToXlsx ( FileName ,options ); } else { XlsExportOptions options = new XlsExportOptions ( ); link . ExportToXls ( FileName ,options ); } if ( DevExpress . XtraEditors . XtraMessageBox . Show ( "儲存成功,是否開啟檔案。" ,"提示" ,MessageBoxButtons . YesNo ,MessageBoxIcon . Information ) == DialogResult . Yes ) System . Diagnostics . Process . Start ( FileName );//開啟指定路徑下的檔案 } catch ( Exception ex ) { DevExpress . XtraEditors . XtraMessageBox . Show ( ex . Message ); } } /// <summary> /// 建立列印Componet /// </summary> /// <param name="printable"></param> /// <returns></returns> static PrintableComponentLink CreatePrintableLink ( IPrintable printable ) { ChartControl chart = printable as ChartControl; if ( chart != null ) chart . OptionsPrint . SizeMode = DevExpress . XtraCharts . Printing . PrintSizeMode . Stretch; PrintableComponentLink printableLink = new PrintableComponentLink ( ) { Component = printable }; return printableLink; } }調用方法:
ViewExport . ExportToExcel ( "GridControl內容匯出" ,gridControl1 );