Merging Multiple Excel Files Into Single Excel File Using NPOI

After lots of searching I developed this application merging multiple Excel files into single Excel files for .Xls extensions.

 

Suppose, An Excel file ‘A’ has 3sheets (SheetA1,SheetA2,SheetA3) and another excel file ‘B’ has 2sheets (SheetB1,sheetB2) now we want to merge both Excel files into a single Excel file with all 5 sheets like (SheetA1,SheetA2,SheetA3,SheetB1,SheetB2)

Step 1

Download the NPOI dlls from https://npoi.codeplex.com/releases

Or

Download the Source file which I provided there you will find the Reference folder having related NPOI dlls.

Step 2

Create Design page

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>  
  2.     <!DOCTYPE html>  
  3.     <html xmlns="http://www.w3.org/1999/xhtml">  
  4.   
  5.     <head runat="server">  
  6.         <title>::EXCEL MERGE::</title>  
  7.         <style>  
  8.             td {  
  9.                 padding: 10px;  
  10.             }  
  11.         </style>  
  12.     </head>  
  13.   
  14.     <body style="font-family:Tahoma; background-color:#c5d6ff">  
  15.         <form id="form1" runat="server">  
  16.             <%--<div>  
  17.   
  18. <asp:Button ID="btnNPOI" runat="server" Text="click NPOI" OnClick="btnNPOI_Click" />  
  19.   
  20. </div>  
  21.   
  22. <div>  
  23.   
  24. <asp:LinkButton ID="lbtndwnld" runat="server" OnClick="lbtndwnld_Click" Text="Download"></asp:LinkButton>  
  25.   
  26. </div>--%>  
  27.                 <div style="width:100%" align="center">  
  28.                     <table width="40%" style="background-color:#f2f2f2;padding:0px; margin:0px;">  
  29.                         <tr>  
  30.                             <td colspan="3" style="background-color:#1d1d1d; color:#c5d6ff; padding:10px;" align="center"> <label style="font-size:1.5em; font-weight:bold">Excel File Merging</label></td>  
  31.                         </tr>  
  32.                         <tr>  
  33.                             <td colspan="3" style="padding:10px;"> </td>  
  34.                         </tr>  
  35.                         <tr>  
  36.                             <td width="30%"> Choose Files </td>  
  37.                             <td> : </td>  
  38.                             <td width="70%" align="left">  
  39.                                 <asp:FileUpload ID="Fuploads" Multiple="Multiple" runat="server" /> </td>  
  40.                         </tr>  
  41.                         <tr>  
  42.                             <td colspan="3" align="center">  
  43.                                 <asp:Panel ID="pnlbody" runat="server" Width="100%">  
  44.                                     <asp:GridView ID="grvfileslist" runat="server" AutoGenerateColumns="False" GridLines="None" DataKeyNames="ID" CellPadding="0" BackColor="White" Font-Size="Small" Font-Underline="False" ForeColor="#3333CC" HorizontalAlign="Left" Width="100%" OnRowDeleting="grvfileslist_RowDeleting">  
  45.                                         <Columns>  
  46.                                             <asp:BoundField DataField="fileName" HeaderStyle-Font-Bold="true" ItemStyle-Width="100%" HeaderText="  List of Files">  
  47.                                                 <HeaderStyle Font-Bold="True" BackColor="#FFFFCC" Font-Size="Medium" Font-Underline="False" ForeColor="#CC0000" BorderStyle="None" Font-Strikeout="False" Height="30px" HorizontalAlign="Left" VerticalAlign="Middle"></HeaderStyle>  
  48.                                                 <ItemStyle Width="100%" Font-Underline="True" BorderStyle="None"></ItemStyle>  
  49.                                             </asp:BoundField>  
  50.                                             <asp:TemplateField ShowHeader="False" Visible="true">  
  51.                                                 <ItemTemplate>  
  52.                                                     <asp:ImageButton ID="btnDel" CommandName="Delete" runat="server" ImageUrl="~/Excel/DeleteRed.png" CausesValidation="false" Visible="true" /> </ItemTemplate>  
  53.                                             </asp:TemplateField>  
  54.                                         </Columns>  
  55.                                     </asp:GridView>  
  56.                                     <asp:LinkButton ID="lbtdownload" runat="server" OnClick="lbtdownload_Click" Visible="false">Download!</asp:LinkButton> <br /><br /><br />  
  57.                                     <asp:Button ID="btnrunAgain" runat="server" Visible="false" Text="Merge Again" OnClick="btnrunAgain_Click" /> </asp:Panel>  
  58.                             </td>  
  59.                         </tr>  
  60.                         <tr>  
  61.                             <td colspan="3" align="right">  
  62.                                 <div style="padding:5px; margin:5px; float:left;" id="divop1" runat="server">  
  63.                                     <asp:CheckBox id="chkop1" runat="server" Text="" OnCheckedChanged="chkop1_CheckedChanged" Checked="true" AutoPostBack="true" />  
  64.                                     <asp:Button runat="server" ID="btnUpload" Text="Upload Files" OnClick="btnUpload_Click" Enabled="false" />   
  65.                                     <asp:Button runat="server" ID="btnMerge" Text="Merge Files" OnClick="btnMerge_Click" Enabled="false" />  </div>  
  66.                                 <div style="padding:5px; margin:5px; float:left" id="divop2" runat="server">  
  67.                                     <asp:CheckBox id="chkop2" runat="server" Text="" OnCheckedChanged="chkop2_CheckedChanged" Checked="false" AutoPostBack="true" />  
  68.                                     <asp:Button ID="btnclick" Text="Upload & Merge" runat="server" OnClick="btnclick_Click" Enabled="false" />   
  69.                                     <asp:Button ID="btnclear" runat="server" Text="Clear" OnClick="btnclear_Click" /> </div>  
  70.                             </td>  
  71.                         </tr>  
  72.                     </table>  
  73.                 </div>  
  74.         </form>  
  75.     </body>  
  76.   
  77.     </html>  

Step 2

Browse Multiple Excel files from FileUpload and Upload. Save all the paths in List<string> and display list of uploaded files in Gridview

  1. public class fileList {  
  2.     public string fileName {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public int ID {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string path {  
  11.         get;  
  12.         set;  
  13.     }  
  14. }  
  15. bool uploadFiles() {  
  16.     bool hasFiles = false;  
  17.     if (Fuploads.HasFile) {  
  18.         hasFiles = true;  
  19.         if (SourceFilePaths == null) {  
  20.             HttpFileCollection flImages = Request.Files;  
  21.             SourceFilePaths = new List < string > ();  
  22.             lstFiles = new List < fileList > ();  
  23.             for (int x = 0; x < flImages.Keys.Count; x++) {  
  24.                 HttpPostedFile flfile = flImages[x];  
  25.                 flfile.SaveAs(Server.MapPath(uploadPath) + flfile.FileName);  
  26.                 SourceFilePaths.Add(Server.MapPath(uploadPath) + flfile.FileName);  
  27.                 Session["SourceFilepaths"] = SourceFilePaths;  
  28.                 obj = new fileList();  
  29.                 obj.fileName = flfile.FileName;  
  30.                 obj.path = Server.MapPath(uploadPath) + flfile.FileName;  
  31.                 obj.ID = x;  
  32.                 lstFiles.Add(obj);  
  33.                 Session["lstFiles"] = lstFiles;  
  34.             }  
  35.             fillGrid();  
  36.             btnMerge.Enabled = true;  
  37.         } else if (SourceFilePaths.Count > 0) {  
  38.             HttpFileCollection flImages = Request.Files;  
  39.             for (int x = 0; x < flImages.Keys.Count; x++) {  
  40.                 HttpPostedFile flfile = flImages[x];  
  41.                 flfile.SaveAs(Server.MapPath(uploadPath) + flfile.FileName);  
  42.                 SourceFilePaths.Add(Server.MapPath(uploadPath) + flfile.FileName);  
  43.                 Session["SourceFilepaths"] = SourceFilePaths;  
  44.                 obj = new fileList();  
  45.                 obj.fileName = flfile.FileName;  
  46.                 obj.path = Server.MapPath(uploadPath) + flfile.FileName;  
  47.                 obj.ID = lstFiles.Count + 1;  
  48.                 lstFiles.Add(obj);  
  49.                 Session["lstFiles"] = lstFiles;  
  50.             }  
  51.             SourceFilePaths = (List < string > ) Session["SourceFilepaths"];  
  52.             lstFiles = (List < fileList > ) Session["lstFiles"];  
  53.             fillGrid();  
  54.             btnMerge.Enabled = true;  
  55.         }  
  56.     }  
  57.     return hasFiles;  
  58. }  
  59. void fillGrid() {  
  60.     grvfileslist.DataSource = lstFiles;  
  61.     grvfileslist.DataBind();  
  62. }  

Step 3

If you want to remove the file from the list click delete icon for this write the code in gridview_RowDeleting event.

  1. protected void grvfileslist_RowDeleting(object sender, GridViewDeleteEventArgs e) {  
  2.     ((List < string > ) Session["SourceFilepaths"]).RemoveAt(e.RowIndex);  
  3.     ((List < fileList > ) Session["lstFiles"]).RemoveAt(e.RowIndex);  
  4.     grvfileslist.DataSource = ((List < fileList > ) Session["lstFiles"]);  
  5.     grvfileslist.DataBind();  
  6. }  

Step 4

Then Merge button will enable; click the Merge button to merge listed multiple Excel files into single ‘Result.xls’ file, but before this create a Results Folder and create an empty Result.xls file in Results Folder.

  1. protected void btnMerge_Click(object sender, EventArgs e) {  
  2.     SourceFilePaths = (List < string > ) Session["SourceFilepaths"];  
  3.     DoMerge(SourceFilePaths);  
  4.     Clear();  
  5.     DeleteupFiles();  
  6.     lbtdownload.Visible = true;  
  7.     btnrunAgain.Visible = true;  
  8.     divop1.Visible = false;  
  9.     divop2.Visible = false;  
  10. }  
  11. void DoMerge(List < string > _sourceFiles) {  
  12.     bool b = false;  
  13.     int i = 0;  
  14.     foreach(string strFile in _sourceFiles) {  
  15.         i = i + 1;  
  16.         NPOICOPY(strFile, i);  
  17.     }  
  18. }  
  19. HSSFWorkbook product = new HSSFWorkbook();  
  20. void NPOICOPY(string filename, int X) {  
  21.     byte[] byteArray = File.ReadAllBytes(filename);  
  22.     using(MemoryStream stream = new MemoryStream()) {  
  23.         stream.Write(byteArray, 0, (int) byteArray.Length);  
  24.         HSSFWorkbook book1 = new HSSFWorkbook(stream);  
  25.         if (X == 1) {  
  26.             product = new HSSFWorkbook();  
  27.         }  
  28.         for (int i = 0; i < book1.NumberOfSheets; i++) {  
  29.             HSSFSheet sheet1 = book1.GetSheetAt(i) as HSSFSheet;  
  30.             sheet1.CopyTo(product, sheet1.SheetName, truetrue);  
  31.         }  
  32.         using(FileStream fs = new FileStream(Server.MapPath(@ "\Results\Result.xls"), FileMode.Create, FileAccess.Write)) {  
  33.             product.Write(fs);  
  34.         }  
  35.     }  
  36. }  
  37. void Clear() {  
  38.     chkop1.Checked = true;  
  39.     chkop2.Checked = false;  
  40.     btnclick.Enabled = false;  
  41.     btnUpload.Enabled = true;  
  42.     btnMerge.Enabled = false;  
  43.     btnUpload.Text = "Upload Files";  
  44.     grvfileslist.DataSource = null;  
  45.     grvfileslist.DataBind();  
  46.     Session["SourceFilepaths"] = null;  
  47.     Session["lstFiles"] = null;  
  48.     lbtdownload.Visible = false;  
  49.     btnrunAgain.Visible = false;  
  50.     divop1.Visible = true;  
  51.     divop2.Visible = true;  
  52. }  
  53. public void DeleteupFiles() {  
  54.     System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath(uploadPath));  
  55.     foreach(FileInfo file in di.GetFiles()) {  
  56.         if (file.Name != "Result.xls") {  
  57.             file.Delete();  
  58.         }  
  59.     }  
  60.     foreach(DirectoryInfo dir in di.GetDirectories()) {  
  61.         dir.Delete(true);  
  62.     }  
  63. }  

Step 5

If Merge has no errors download link will appear click the download button to download the result file.

  1. protected void lbtdownload_Click(object sender, EventArgs e) {  
  2.     download(@ "\Results\Result.xls");  
  3. }  
  4. public void download(string destFile) {  
  5.     string filePath = Server.MapPath(destFile);  
  6.     Response.ContentType = ContentType;  
  7.     Response.AppendHeader("Content-Disposition""attachment; filename=" + Path.GetFileName(filePath));  
  8.     Response.WriteFile(filePath);  
  9.     Response.End();  
  10. }  

If you want to upload & merge directly all at one  time just write the code below

  1. protected void btnclick_Click(object sender, EventArgs e) {  
  2.     SourceFilePaths = null;  
  3.     if (uploadFiles()) {  
  4.         DoMerge(SourceFilePaths);  
  5.         Clear();  
  6.         DeleteupFiles();  
  7.         lbtdownload.Visible = true;  
  8.         btnrunAgain.Visible = true;  
  9.         divop1.Visible = false;  
  10.         divop2.Visible = false;  
  11.     } else {  
  12.         TestWebMsgApp.WebMsgBox.Show("No Files to Merge. Please select the files to Upload & Merge !");  
  13.     }  
  14. }  

Hope this will help for merging.

If this article was helpful please comment below.

Ebook Download
View all
Learn
View all