I loop source files
open file and the only worksheet
get the source range as worksheet use range
setup subsequent destination range
and add it to destination qorkbook and save it
after some files can’t determine exactly the number when number of rows became high
I get exception
System.ArgumentOutOfRangeException:
at line
IRange destinationRange = destinationWorksheet.Range[currentDestFirstRow,currentDestFirstCol, currentDestLastRow, currentDestLastCol];
wih the following value
destination range=[1037502,1,1047586,6]
If I stop loop after some files everything goes well
and destination file is generated correctly.
beware that range parameters are int I don’t find any reason to be out of range.
Thanks for any suggestion
public Test()
{
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("my_key");
destinationFile = outputDataPath + "__merged.xlsx";
//get list of file to merge
filesToMerge = Directory.GetFiles(this.inputDatapath, "*.xlsx");
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
/* set destination workbook and worksheet
* initialize destination Range
*/
IWorkbook destinationWorkbook = application.Workbooks.Create(1);
IWorksheet destinationWorksheet = destinationWorkbook.Worksheets[0];
int currentDestFirstRow = 1;
int currentDestFirstCol = 1;
int currentDestLastRow=1;
int currentDestLastCol;
string currentFile;
for(int i = 0; i < filesToMerge.Length - 1; i++)
{
/*get used range from worksheet of each input file
* and copy to destination*/
currentFile = filesToMerge[i];
FileStream currentStream = new FileStream(currentFile, FileMode.Open, FileAccess.Read);
IWorkbook currentWorkbook = application.Workbooks.Open(currentStream, ExcelOpenType.Automatic);
IWorksheet currentWorksheet = currentWorkbook.Worksheets[0];
IRange currentSourceRange = currentWorksheet.UsedRange;
if (i == 0)
{
currentDestFirstRow = 1;
currentDestFirstCol = 1;
currentDestLastRow = currentSourceRange.LastRow;
currentDestLastCol = currentSourceRange.LastColumn;
}
else
{
currentDestFirstRow = currentDestLastRow + 1;
currentDestFirstCol = 1;
currentDestLastRow= currentDestFirstRow + currentSourceRange.LastRow;
currentDestLastCol = currentSourceRange.LastColumn;
}
IRange destinationRange = destinationWorksheet.Range[currentDestFirstRow, currentDestFirstCol, currentDestLastRow, currentDestLastCol];
currentSourceRange.CopyTo(destinationRange);
string line = (i.ToString()).PadLeft(3, '0')+Environment.NewLine;
line += $"file={currentFile}" + Environment.NewLine;
line += $"destination range=[{currentDestFirstRow},{currentDestFirstCol},{currentDestLastRow},{currentDestLastCol}]";
Console.WriteLine(line);
}
FileStream stream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
destinationWorkbook.SaveAs(stream);
destinationWorkbook.Close();
stream.Close();
excelEngine.Dispose();
}