1- // See https://aka.ms/new-console-template for more information
2- using Syncfusion . XlsIO ;
3-
1+ using Syncfusion . XlsIO ;
42
53namespace MergeExcel
64{
75 class Program
86 {
97 static void Main ( string [ ] args )
108 {
11- string inputPath = @"../../../Data/" ;
12-
13- string outputPath = @"../../../Output/" ;
9+ string inputPath = Path . GetFullPath ( "Data" ) ;
10+ string outputPath = Path . GetFullPath ( "Output" ) ;
1411
1512 FileInfo [ ] files = new DirectoryInfo ( inputPath ) . GetFiles ( ) ;
1613
17- List < Stream > streams = new List < Stream > ( ) ;
18-
19- foreach ( FileInfo file in files )
20- {
21- streams . Add ( file . OpenRead ( ) ) ;
22- }
23-
24- Stream mergedStream = MergeExcelDocuments ( streams ) ;
25-
26- FileStream fileStream = new FileStream ( Path . GetFullPath ( outputPath + "MergedExcel.xlsx" ) , FileMode . Create , FileAccess . Write ) ;
27- mergedStream . Position = 0 ;
28- mergedStream . CopyTo ( fileStream ) ;
29- fileStream . Close ( ) ;
30- }
31-
32- /// <summary>
33- /// Merge Excel documents from the list of Excel streams
34- /// </summary>
35- /// <param name="streams">List of Excel document stream to be merged</param>
36- /// <returns></returns>
37- public static Stream MergeExcelDocuments ( List < Stream > streams )
38- {
3914 using ( ExcelEngine excelEngine = new ExcelEngine ( ) )
4015 {
4116 IApplication application = excelEngine . Excel ;
4217 application . DefaultVersion = ExcelVersion . Xlsx ;
43- IWorkbook workbook = application . Workbooks . Create ( 0 ) ;
4418
45- //Loop through each Excel document and add the worksheets to the new workbook
46- foreach ( Stream stream in streams )
19+ IWorkbook mergedBook = application . Workbooks . Create ( 0 ) ;
20+
21+ foreach ( FileInfo file in files )
4722 {
48- stream . Position = 0 ;
49- IWorkbook tempWorkbook = application . Workbooks . Open ( stream ) ;
50- workbook . Worksheets . AddCopy ( tempWorkbook . Worksheets ) ;
23+ IWorkbook tempWorkbook = application . Workbooks . Open ( Path . GetFullPath ( file . FullName ) ) ;
24+ mergedBook . Worksheets . AddCopy ( tempWorkbook . Worksheets ) ;
5125 tempWorkbook . Close ( ) ;
5226 }
5327
54- //Save the workbook to a memory stream
55- MemoryStream memoryStream = new MemoryStream ( ) ;
56- workbook . Version = ExcelVersion . Xlsx ;
57- workbook . SaveAs ( memoryStream ) ;
58-
59- return memoryStream ;
28+ mergedBook . Version = ExcelVersion . Xlsx ;
29+ mergedBook . SaveAs ( Path . GetFullPath ( Path . Combine ( outputPath , "MergedExcel.xlsx" ) ) ) ;
6030 }
6131 }
6232 }
63- }
64-
65-
66-
67-
68-
69-
70-
33+ }
0 commit comments