Hi rani,
Check this example. Now please take its reference and correct your code.
For exporting to word you need to install sautinsoft.document library from nuget.
Refer below link.
sautinsoft.document
Namespaces
using System.IO;
using SautinSoft.Document;
Controller
public class HomeController : Controller
{
private IWebHostEnvironment Environment;
public HomeController(IWebHostEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3]
{
new DataColumn("Id", typeof(string)),
new DataColumn("Name", typeof(string)),
new DataColumn("BirthDate", typeof(DateTime))
});
dt.Rows.Add(1, "Nancy Davolio", "1948-12-08");
dt.Rows.Add(2, "Andrew Fuller", "1952-02-19");
dt.Rows.Add(3, "Janet Leverling", "1963-08-30");
dt.Rows.Add(4, "Margaret Peacock", "1937-09-19");
DataTable dtChart = new DataTable();
dtChart.Columns.AddRange(new DataColumn[]
{
new DataColumn("Product", typeof(string)),
new DataColumn("Total", typeof(int))
});
dtChart.Rows.Add("Chair", 56);
dtChart.Rows.Add("Table", 69);
dtChart.Rows.Add("Stool", 5);
ViewBag.Product = string.Join(",", dtChart.AsEnumerable().Select(r => r.Field<string>("Product")).ToArray());
ViewBag.Total = string.Join(",", dtChart.AsEnumerable().Select(r => r.Field<int>("Total")).ToArray());
return View(dt);
}
[HttpPost]
public FileResult Chart(string hfHTML, string hfChartData)
{
byte[] bytesImage = Convert.FromBase64String(hfChartData.Replace("data:image/jpeg;base64,", ""));
string wwwPath = this.Environment.WebRootPath;
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
System.IO.File.WriteAllBytes(path + "\\Chart.jpg", bytesImage);
string html = String.Format("{0}<div> </div><img src='{1}' height='300' width='400' />", hfHTML, path + "\\Chart.jpg");
string input = Path.Combine(path, "html1.html");
string output = Path.Combine(path, "Grid.docx");
System.IO.File.WriteAllText(input, html);
DocumentCore documentCore = DocumentCore.Load(input);
documentCore.Save(output);
byte[] bytes = System.IO.File.ReadAllBytes(output);
Directory.Delete(path, true);
return File(bytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Grid.docx");
}
}
View
@model System.Data.DataTable
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.3.3/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/datetime/1.0.2/js/dataTables.dateTime.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.3.3/css/select.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/datetime/1.0.2/css/dataTables.dateTime.min.css" />
<script type="text/javascript">
$.fn.dataTable.render.moment = function (from, to, locale) {
// Argument shifting
if (arguments.length === 1) {
locale = 'en';
to = from;
from = 'DD-MM-YYYY';
}
else if (arguments.length === 2) {
locale = 'en';
}
return function (d, type, row) {
if (!d) {
return type === 'sort' || type === 'type' ? 0 : d;
}
var m = window.moment(d, from, locale, false);
return m.format(type === 'sort' || type === 'type' ? 'x' : to);
};
};
$(document).ready(function () {
$("#myTable").dataTable({
bLengthChange: true,
lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
bFilter: true,
bSort: true,
bPaginate: true,
columns: [
{ data: 'Id' },
{ data: 'Name' },
{ data: 'BirthDate', render: $.fn.dataTable.render.moment('MM/DD/YYYY') }
],
})
})
</script>
</head>
<body>
@using (Html.BeginForm("Chart", "Home", FormMethod.Post))
{
<input type="hidden" name="hfHTML" value="" />
<input type="hidden" name="hfChartData" value="" />
<button id="download" type="submit">Download</button>
}
<div id="dvData">
<section class="content">
<div class="container-fluid">
<table class="table table-bordered table-responsive-lg table-hover" width="100%" id="myTable">
<thead class="thead-dark text-center">
<tr>
<th>Id</th>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody class="text-center">
@for (int i = 0; i < Model.Rows.Count; i++)
{
<tr>
<td>@Model.Rows[i]["Id"]</td>
<td>@Model.Rows[i]["Name"]</td>
<td>
@Convert.ToDateTime(Model.Rows[i]["BirthDate"]).ToString("dd/MM/yyyy")
</td>
</tr>
}
</tbody>
</table>
</div>
</section>
<div class="box-body">
<div class="chart-container">
<canvas id="chart" style="width:50%; height:50%"></canvas>
</div>
</div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script type="text/javascript">
$(function () {
var labels = '@ViewBag.Product';
var datas ='@ViewBag.Total';
var labelsArray = new Array();
var dataArray = new Array();
var colorArray = new Array();
for (var i = 0; i < labels.split(',').length; i++) {
labelsArray.push(labels.split(',')[i]);
dataArray.push(datas.split(',')[i]);
colorArray.push(getRandomColor());
}
new Chart(document.getElementById("chart").getContext('2d'), {
type: 'pie',
data: {
labels: labelsArray,
datasets: [{
backgroundColor: colorArray,
data: dataArray
}]
}
});
});
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
document.getElementById("download").addEventListener("click", function () {
var imgData = document.getElementById('chart').toDataURL("image/jpeg", 1.0);
document.getElementsByName('hfHTML')[0].value = document.getElementById('myTable').outerHTML;
document.getElementsByName('hfChartData')[0].value = imgData;
}, false);
</script>
</body>
</html>