How to Compress Excel Files to ZIP in C#

How to Compress Excel Files to ZIP in C#

The ZIP archives can contain multiple files and are commonly used to reduce file size. Each file is compressed individually, allowing you to extract or add files without processing the entire archive. Excel spreadsheets (XLSX or XLS) are widely used in business, and large files can be shrunk by compressing them into a ZIP archive. This article shows how to compress Excel files to a ZIP archive in C# and how to report compression progress while zipping large Excel files.

The following points are covered:

C# .NET API to compress Excel files to a ZIP archive

To create a ZIP archive with Excel files, we use Aspose.ZIP for .NET. The API offers many archiving features. Download the DLL or install it via NuGet.

Install-Package Aspose.ZIP

Add XLS or XLSX files to ZIP in C#

Suppose you have several Excel (XLSX or XLS) files to compress. You can choose one of the following methods.

C# compress Excel files to ZIP using FileStream

This method uses the FileStream class and calls Archive.CreateEntry(String, FileStream).

Steps:

  1. Create a FileStream for the output ZIP archive.
  2. Create FileStream objects for each Excel file.
  3. Initialize the Archive class with an ArchiveEntrySettings instance.
  4. Add the file streams from step 2 with Archive.CreateEntry.
  5. Call Archive.Save using the output FileStream and an ArchiveSaveOptions instance.

C# compress XLSX or XLS files into ZIP using FileInfo

Alternatively, use the FileInfo class. Files are loaded with FileInfo and added via Archive.CreateEntry(String, FileInfo).

Steps:

  1. Create a FileStream for the output ZIP archive.
  2. Create FileInfo objects for the Excel files.
  3. Initialize the Archive class with an ArchiveEntrySettings instance.
  4. Add the file info objects from step 2 with Archive.CreateEntry.
  5. Call Archive.Save using the output FileStream and an ArchiveSaveOptions instance.

Compress Excel spreadsheets to ZIP using the file path

The simplest approach adds an Excel file path directly to Archive.CreateEntry.

Steps:

Get the report of compression progress in C#

Large Excel files may take time to compress. The C# ZIP compression library offers a [CompressionProgressed] event to provide continuous updates.

Steps:

Get a Free License

You can get a free temporary license to test the API without evaluation limitations.

Conclusion

In this article, you learned how to compress Excel files to a ZIP archive in C# using a C# ZIP compression library. You also saw how to obtain a compression progress report while zipping large Excel files. Visit the documentation to explore additional features of the C# ZIP compression API.

Ask a question

You can let us know your questions or queries on our forum.

See Also