Search code examples
asp.net-mvcweb-servicesfilestreamhttphandler

Stream multiple Excel files as one file


I want to deliver large Excel files using a webservice or httphandler.

As the Excel files can be very big in size, I want to split them up into smaller files, to decrease the memory footprint.

So I will have a master excelfile that contains the column headers and data. And further files which will only contain data.

During download, I want to stream the master excel file first and then append all other related excel files as one download stream. I don't want to zip them! It should be one file at the end

Is this possible?


Master excel file with headers: enter image description here

All other files will look like this (without headers): enter image description here

This will indeed return crap:

void Main()
{
    CombineMultipleFilesIntoSingleFile();
}

// Define other methods and classes here

    private static void CombineMultipleFilesIntoSingleFile(string outputFilePath= @"C:\exceltest\main.xlsx", string inputDirectoryPath = @"C:\exceltest", string inputFileNamePattern="*.xlsx")
    {
        string[] inputFilePaths = Directory.GetFiles(inputDirectoryPath, inputFileNamePattern);
        Console.WriteLine("Number of files: {0}.", inputFilePaths.Length);
        using (var outputStream = File.Create(outputFilePath))
        {
            foreach (var inputFilePath in inputFilePaths)
            {
                using (var inputStream = File.OpenRead(inputFilePath))
                {
                    // Buffer size can be passed as the second argument.
                    inputStream.CopyTo(outputStream);
                }
                Console.WriteLine("The file {0} has been processed.", inputFilePath);
            }
        }
    }

Solution

  • When you are requesting for file, do not download it at first request.

    1. Request for file names to be downloaded in AJAX request.
    2. For each file name received, prepare its path to the server.
    3. Create hidden iFrames for each file path and specify src as file path for each file to be downloaded.

    When iFrame's src attribute is set, it will navigate to the file path and each iFrame will download single file, so multiple iFrame downloads multiple files.

    You cannot download multiple files in single request. As if you will append the stream of multiple files, it will create a garbage file, a single garbage file.