Hi rani,
Check this example. Now please take its reference and correct your code.
Install OpenXml from nuget.
Namespaces
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
Controller
public class HomeController : Controller
{
private IHostingEnvironment Environment;
public HomeController(IHostingEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(List<IFormFile> postedFiles)
{
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
List<string> uploadedFiles = new List<string>();
foreach (IFormFile postedFile in postedFiles)
{
string fileName = Path.GetFileName(postedFile.FileName);
using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
{
postedFile.CopyTo(stream);
uploadedFiles.Add(Path.Combine(path, fileName));
}
}
string newFilePath = Path.Combine(path, "Merge.docx");
// Create blank document.
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(newFilePath, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
}
for (int i = 0; i < uploadedFiles.Count; i++)
{
using (WordprocessingDocument wpd = WordprocessingDocument.Open(newFilePath, true))
{
MainDocumentPart mdp = wpd.MainDocumentPart;
string altChunkId = "AltChunkId" + i;
AlternativeFormatImportPart chunk = mdp.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
using (FileStream fileStream = System.IO.File.Open(uploadedFiles[i], FileMode.Open))
{
chunk.FeedData(fileStream);
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mdp.Document.Body.InsertAfter(altChunk, mdp.Document.Body.Elements<Paragraph>().Last());
mdp.Document.Save();
wpd.Close();
}
}
return View();
}
}
View
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
<input type="file" name="postedFiles" multiple />
<input type="submit" value="Upload" />
</form>
</body>
</html>