1 string fileName = AppDomain.CurrentDomain.BaseDirectory + "1.xls"; 2 Excel.Application xApp = new Excel.ApplicationClass(); 3 xApp.Visible = false; 4 xApp.AlertBeforeOverwriting = false;//覆蓋不彈窗 5 xApp.DisplayAlerts = false; 6 Excel.Workbook xBook = xApp.Workbooks._Open(fileName, 7 Missing.Value, Missing.Value, Missing.Value, Missing.Value 8 , Missing.Value, Missing.Value, Missing.Value, Missing.Value 9 , Missing.Value, Missing.Value, Missing.Value, Missing.Value); 10 Excel.Worksheet xSheet = (Excel.Worksheet)xBook.Sheets[1]; 11 //關鍵代碼 12 Range range = xSheet.get_Range(xSheet.Cells[4, 1], xSheet.Cells[7, 1]); 13 range.Rows.Select(); 14 range.Rows.Group(Type.Missing, Type.Missing, Type.Missing, Type.Missing); 15 xSheet.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "2.xls", //保存路徑也可為上面打開的路徑 16 Excel.XlFileFormat.xlExcel7, //指定保存格式 17 Missing.Value, 18 Missing.Value, 19 Missing.Value, 20 Missing.Value, 21 Excel.XlSaveAsAccessMode.xlShared, 22 Missing.Value, Missing. 23 Value, Missing.Value); 24 //關閉Excel 25 xSheet = null; 26 xBook = null; 27 xApp.Quit(); //這一句是非常重要的,否則Excel對象不能從內存中退出 28 xApp = null; 29 GC.Collect(); 30 System.GC.WaitForPendingFinalizers();
Aspose Cells是一款Excel文檔處理控件,可以對Excel文件進行創建、處理、轉換和各種操作,幾乎可以實現Microsoft Excel一樣的功能,在Excel里可以在數據區域范圍外創建數據分組,當用戶點擊分組按鈕時可以進行分組和顯示。Aspose Cells提供一個類Workbook,里面包含了一系列函數和方法,GroupRows 和 GroupColumns 方法就是用於進行分組。
下面的事例簡單介紹了分組行和列: //Creating a file stream containing the Excel file to be opened FileStream fstream = new FileStream("C:\\book1.xls", FileMode.Open); //Instantiating a Workbook object //Opening the Excel file through the file stream Workbook workbook = new Workbook(fstream); //Accessing the first worksheet in the Excel file Worksheet worksheet = workbook.Worksheets[0]; //Grouping first six rows (from 0 to 5) and making them hidden by passing true worksheet.Cells.GroupRows(0, 5, true); //Grouping first three columns (from 0 to 2) and making them hidden by passing true worksheet.Cells.GroupColumns(0, 2, true); //Saving the modified Excel file workbook.Save("C:\\output.xls"); //Closing the file stream to free all resources fstream.Close(); 同樣地可以控制是否統計行是否顯示 worksheet.Outline.SummaryRowBelow = false; worksheet.Outline.SummaryColumnRight = false;