Как объединить несколько файлов Excel в один файл с одним листом на C# с помощью Syncfusion.XlsIOC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Как объединить несколько файлов Excel в один файл с одним листом на C# с помощью Syncfusion.XlsIO

Сообщение Anonymous »

Я зацикливаю исходные файлы, открываю файл и единственный рабочий лист, получаю исходный диапазон в качестве диапазона использования рабочего листа, настраиваю последующий целевой диапазон, добавляю его в целевую книгу и сохраняю.
После того, как некоторые файлы не могут точно определить число, когда количество строк стало большим, я получаю исключение

System.ArgumentOutOfRangeException:

в строке
IRange destinationRange = destinationWorksheet.Range[currentDestFirstRow,currentDestFirstCol, currentDestLastRow, currentDestLastCol];

со следующим значением
destination range=[1037502,1,1047586,6]

Если я останавливаю цикл после некоторых файлов, все идет хорошо, и целевой файл генерируется правильно.
Остерегайтесь того, что параметры диапазона имеют тип int, я этого не делаю. найдите любую причину выхода за пределы допустимого диапазона.
Спасибо за любые предложения
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;

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();
}
}


Подробнее здесь: https://stackoverflow.com/questions/784 ... -sharp-usi
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»