How to create redar diagram in excel using Epplus in dotnet 6 - c#

I have created report in excel sheet which Is described in image1 and this image should give redar diagram which in in Image2 in different excel sheet like given in screenshot.
there are two excel sheet in one excel as you can see in screenshot so in chart sheet there should be redar diagram and sheet named sheet there is excel report valud as you can see in screenshot
I have already done piechart and excel report as well and I get stocked while making redar diagram ,
example of that I had made piechart and excel report :
public static class TestRunTestCaseExportHelper {
public static byte[] TestRunTestCaseByTestRunIdToExcel(List<TestRunTestCaseExportModel> data1, List<TestRunTestCaseExportTestResultCountModel> datas, List<FunctionModuleModel> funcitonData, TestRunTestCaseCountPercentageModel testRunStatusCountPercentage)
{
try
{
byte[] result;
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package = new ExcelPackage())
{
int cellNumb = 1;
string[] totalColumns = {
"SN",
"Test Case",
"Test Plan",
"Status"
};
string[] totalColumn = {
"Test Plan",
"Passed",
"Failed",
"Pending",
"Blocked",
};
string[] totalColumn3 = {
"Function",
"Count"
};
string[] totalColumn4 = {
"Status",
"Percentage",
};
var worksheet = package.Workbook.Worksheets.Add("Chart");
var worksheets = package.Workbook.Worksheets.Add("sheet");
//worksheet.InsertRow(5, 2);
var rand = new Random();
var testRunStatusCountPercentages = testRunStatusCountPercentage;
var data = new List<KeyValuePair<string, int>>
{
new KeyValuePair<string, int>("Passed", testRunStatusCountPercentages.PassedPercentage),
new KeyValuePair<string, int>("Failed", testRunStatusCountPercentages.FailedPercentage),
new KeyValuePair<string, int>("Pending",85),
new KeyValuePair<string, int>("Blocked", 15),
};
for (var i = 0; i < totalColumn4.Length; i++)
{
worksheets.Cells[1, i + 16].Value = totalColumn4[i]; //populate header row
}
var m = 2;
//Fill the table
var startCell = worksheets.Cells[1, 16];
if (testRunStatusCountPercentage != null)
{
for (var i = 0; i < data.Count(); i++)
{
startCell.Offset(i + 1, 0).Value = data[i].Key;
startCell.Offset(i + 1, 1).Value = data[i].Value;
}
using (ExcelRange Rng = worksheets.Cells[1, 16, 5, data.Count + 13])
{
Rng.Style.Border.Top.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Right.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
}
}
//Add the chart to the sheet
var pieChart = worksheet.Drawings.AddChart("Chart1", eChartType.Pie);
pieChart.SetPosition(data.Count + 1, 0, 0, 0);
pieChart.Title.Text = "Test Case Excution Status";
pieChart.Title.Font.Bold = true;
pieChart.Title.Font.Size = 12;
//Set the data range
var series = pieChart.Series.Add(worksheets.Cells[2, 17, data.Count + 1, 17], worksheets.Cells[2, 16, data.Count + 1, 16]);
var pieSeries = (ExcelPieChartSerie)series;
pieSeries.Explosion = 5;
//Format the labels
pieSeries.DataLabel.Font.Bold = true;
pieSeries.DataLabel.ShowValue = true;
pieSeries.DataLabel.ShowPercent = true;
pieSeries.DataLabel.ShowLeaderLines = true;
pieSeries.DataLabel.Separator = ";";
pieSeries.DataLabel.Position = eLabelPosition.BestFit;
//Format the legend
pieChart.Legend.Add();
pieChart.Legend.Border.Width = 0;
pieChart.Legend.Font.Size = 12;
pieChart.Legend.Font.Bold = true;
pieChart.Legend.Position = eLegendPosition.Right;
// add a new worksheet to the empty workbook
using (var cells = worksheets.Cells[1, 1, 1, totalColumns.Length]) //(1,1) => (1,10)
{
cells.Style.Font.Bold = true;
}
using (var cells = worksheets.Cells[1, 7, 1, totalColumn.Length + 7]) //(1,1) => (1,10)
{
cells.Style.Font.Bold = true;
}
using (var cells = worksheets.Cells[1, 13, 1, totalColumn3.Length + 13]) //(1,1) => (1,10)
{
cells.Style.Font.Bold = true;
}
using (var cells = worksheets.Cells[1, 16, 1, totalColumn4.Length + 16]) //(1,1) => (1,10)
{
cells.Style.Font.Bold = true;
}
var records = data1.ToList();
var list = datas.ToList();
var funValue = funcitonData.ToList();
int totalRows = data1.Count + 1; //data including header row
int totalRowsList = datas.Count + 2;
var totalRowsForFuntion = funcitonData.Count + 1;
for (var i = 0; i < totalColumns.Length; i++)
{
worksheets.Cells[1, i + 1].Value = totalColumns[i]; //populate header row
}
for (var i = 0; i < totalColumn.Length; i++)
{
worksheets.Cells[1, i + 7].Value = totalColumn[i]; //populate header row
}
for (var i = 0; i < totalColumn3.Length; i++)
{
worksheets.Cells[1, i + 13].Value = totalColumn3[i]; //populate header row
}
//Add values
var j = 2; //to start data from second row after the header row.
var k = 2;
var l = 2;
if (data1 != null)
{
foreach (var item in records)
{
worksheets.Cells["A" + j].Value = cellNumb;
worksheets.Cells["B" + j].Value = item.TestCaseName;
worksheets.Cells["C" + j].Value = item.TestPlanName;
worksheets.Cells["D" + j].Value = item.Status;
j++;
cellNumb++;
}
using (ExcelRange Rng = worksheets.Cells[1, 1, totalRows, totalColumns.Length])
{
Rng.Style.Border.Top.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Right.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
}
}
if (datas != null)
{
foreach (var item in datas)
{
worksheets.Cells["G" + k].Value = item.TestPlanNameForCount;
worksheets.Cells["H" + k].Value = item.TotalPassedCount;
worksheets.Cells["I" + k].Value = item.TotalFailedCount;
worksheets.Cells["J" + k].Value = item.TotalPendingCount;
worksheets.Cells["K" + k].Value = item.TotalBlockCount;
k++;
}
worksheets.Cells["G" + k].Value = "Total";
worksheets.Cells["H" + k].Value = datas.Sum(x => x.TotalPassedCount);
worksheets.Cells["I" + k].Value = datas.Sum(x => x.TotalFailedCount);
worksheets.Cells["J" + k].Value = datas.Sum(x => x.TotalPendingCount);
worksheets.Cells["K" + k].Value = datas.Sum(x => x.TotalBlockCount);
using (ExcelRange Rng = worksheets.Cells[1, 7, totalRowsList, totalColumn.Length + 6])
{
Rng.Style.Border.Top.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Right.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
}
}
if (funcitonData != null)
{
foreach (var item in funValue)
{
worksheets.Cells["M" + l].Value = item.FunctionName;
worksheets.Cells["N" + l].Value = item.TotalCountTestCaseByTestRunId;
l++;
}
using (ExcelRange Rng = worksheets.Cells[1, 13, totalRowsForFuntion, totalColumn3.Length + 12])
{
Rng.Style.Border.Top.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Right.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
}
}
worksheets.Cells.AutoFitColumns();
result = package.GetAsByteArray();
return result;
}
}
catch (Exception ex)
{
throw new Exception($"Download failed : {ex.Message}");
}
}
}

var redarChart = worksheet.Drawings.AddRadarChart("RadarChart",
eRadarChartType.RadarMarkers);
redarChart.SetPosition(42, 0, 0, 0);
redarChart.SetSize(700, 300);
redarChart.Title.Text = "Function Map";
redarChart.Title.Font.Bold = true;
redarChart.Title.Font.Size = 12;
var serie = redarChart.Series.Add(worksheets.Cells[2, 14, funValue.Count + 1, 14], worksheets.Cells[2, 13, funValue.Count + 1, 13]);
serie.HeaderAddress = new ExcelAddress("'sheet'!N1");
redarChart.StyleManager.SetChartStyle(ePresetChartStyleMultiSeries.RadarChartStyle4);
redarChart.Fill.Color = System.Drawing.Color.Black;
redarChart.Legend.Position = eLegendPosition.TopRight;
//If you want to apply custom styling do that after setting the chart style so its not overwritten.
redarChart.Legend.Effect.SetPresetShadow(ePresetExcelShadowType.OuterTopLeft);
var radarSeries = (ExcelRadarChartSerie)serie;
radarSeries.Marker.Size = 5;

Related

C# EPPlus how to generate line chart with dash line

For last 2 days I stuck with a line chart issue with EPPlus. My objective is to create a line chart with EPPlus and line style will be dash line like below image. picture attached.
I search a lot Google for 2 days still got no relevant hint to have dash line in chart. I am not sure that at all EPPlus support dash line. I am using EPPlus version 6.0 and .NET Framework version 4.8. This is a sample code which generate chart in excel sheet with one line but I need that line will be dash line. please someone see my code and tell me what is missing in my code for which I could not have dash line style of line chart.
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
var newFile = new FileInfo(filepath);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add("test");
worksheet.Cells["A1"].Value = 1;
worksheet.Cells["A2"].Value = 2;
worksheet.Cells["A3"].Value = 3;
worksheet.Cells["A4"].Value = 4;
worksheet.Cells["A5"].Value = 5;
worksheet.Cells["A6"].Value = 6;
worksheet.Cells["B1"].Value = 10000;
worksheet.Cells["B2"].Value = 10100;
worksheet.Cells["B3"].Value = 10200;
worksheet.Cells["B4"].Value = 10150;
worksheet.Cells["B5"].Value = 10250;
worksheet.Cells["B6"].Value = 10200;
//ExcelChart chart = worksheet.Drawings.AddChart("LineChart", eChartType.XYScatterSmooth);
ExcelChart chart = worksheet.Drawings.AddChart("LineChart", eChartType.XYScatterSmoothNoMarkers);
chart.Series.Add(ExcelRange.GetAddress(1, 2, worksheet.Dimension.End.Row, 2),
ExcelRange.GetAddress(1, 1, worksheet.Dimension.End.Row, 1));
var Series = chart.Series[0];
//chart.Axis[0].MinorGridlines.Fill.Color = Color.Red;
//chart.Axis[0].MinorGridlines.LineStyle = eLineStyle.LongDashDot;
chart.Axis[0].RemoveGridlines();
chart.Axis[1].RemoveGridlines();
chart.Axis[0].Border.LineStyle = eLineStyle.SystemDash;
//chart.XAxis.Border.LineStyle = eLineStyle.Dash;
chart.Series[0].Header = "Blah";
//chart.Series[0].Border.LineStyle = eLineStyle.DashDot;
//chart.Axis[0].Border.LineStyle = eLineStyle.Dash;
xlPackage.Save();
MessageBox.Show("Done");
}
I also check this post but could not implement it in my code Office Open XML: Drawing Dashed Line in Chart
Please push me to right direction to achieve my goal. Thanks in advance.
This works for me with same versions as you.
You need to add a reference to System.Drawing for the color:
// ...(code above this line did not change)
ExcelChart chart = worksheet.Drawings.AddChart("LineChart", eChartType.XYScatterSmoothNoMarkers);
chart.Series.Add(
ExcelRange.GetAddress(1, 2, worksheet.Dimension.End.Row, 2),
ExcelRange.GetAddress(1, 1, worksheet.Dimension.End.Row, 1));
chart.Series[0].Header = "Blah";
// Add this:
chart.Series[0].Border.LineStyle = OfficeOpenXml.Drawing.eLineStyle.Dash;
chart.Series[0].Border.Width = 2;
chart.Series[0].Border.Fill.Color = System.Drawing.Color.Blue;
chart.Axis[0].RemoveGridlines();
chart.Axis[1].RemoveGridlines();
xlPackage.Save();
Result:
#region chart summary 4
ExcelWorksheet Worksheet4 = p.Workbook.Worksheets.Add("Graph(4)");
var summary_Chart_four = Worksheet4.Drawings.AddChart("chart", eChartType.LineMarkers);
// var summary_Chart_four = Worksheet4.Drawings.AddChart("chart", eChartType.XYScatterLines) as ExcelScatterChart;
//var summary_Chart_four = Worksheet4.Drawings.AddChart("chart", (eChartType)System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash);
//var summary_Chart_four = myWorksheet.Drawings.AddChart("chart", (eChartType)System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash);
summary_Chart_four.ShowDataLabelsOverMaximum = true;
Worksheet4.Cells.Style.Font.Name = "Arial";
Worksheet4.Cells.Style.Font.Size = 10;
Worksheet4.Cells.Style.Font.Bold = false;
loopCnt = 0;
for (int i = 0; i < (cVM.PeerGroups.Count + cVM.IndexGroups.Count) * 4; i += 4)
{
int rowIndex = 10 + i;
int endRowIndex = 14 + i;
string startingColumn_series = "C" + rowIndex;
string endColumn_series = column + rowIndex;
string lastColumn_xaxis = column + 6;
int headerRowIndex = 9 + i;
string seriesHeader = "A" + headerRowIndex;
var series_i = summary_Chart_four.Series.Add(myWorksheet_summary_data.Cells[startingColumn_series + ":" + endColumn_series], myWorksheet_summary_data.Cells["C6:" + lastColumn_xaxis]);//working
series_i.Header = myWorksheet_summary_data.Cells[seriesHeader].Value.ToString();
summary_Chart_four.YAxis.Font.Size = 10;
summary_Chart_four.XAxis.Font.Size = 10;
//summary_Chart_four.XAxis.Format =DateTime.Now.Year.ToString();
summary_Chart_four.YAxis.Format = "$0";
if (loopCnt == 0)
{
string LineColor = "#000080";
series_i.Border.LineStyle = eLineStyle.Solid;
//series_i.LineColor = LineColor.ConvertToColor();
//series_i.LineWidth = 2.0;
//series_i.Marker.Style = eMarkerStyle.Diamond;
//series_i.Marker.Size = 8;
//string BGColor = "#99ccff";
//series_i.Marker.Fill.Color = BGColor.ConvertToColor();
//string strBorderColor = "#000080";
//series_i.Marker.Border.Fill.Color = strBorderColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).LineColor = LineColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).LineWidth = 2.0;
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Style = eMarkerStyle.Diamond;
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Size = 8;
string BGColor = "#99ccff";
//((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.LineCap
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Fill.Color = BGColor.ConvertToColor();
string strBorderColor = "#000080";
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.Fill.Color = strBorderColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.Width = 0.75;
}
else if (loopCnt == 1)
{
string LineColor = "#003300";
series_i.Border.LineStyle = eLineStyle.LongDash;
//series_i.LineColor = LineColor.ConvertToColor();
//series_i.LineWidth = 2.0;
//series_i.Marker.Style = eMarkerStyle.Square;
////((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Style = eMarkerStyle.Dash;
//series_i.Marker.Size = 7;
string BGColor = "#c0c0c0";
//series_i.Marker.Fill.Color = BGColor.ConvertToColor();
//string strBorderColor = "#003300";
//series_i.Marker.Border.Fill.Color = strBorderColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).LineColor = LineColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).LineWidth = 2.0;
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Style = eMarkerStyle.Square;
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Size = 7;
//((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.LineCap
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Fill.Color = BGColor.ConvertToColor();
string strBorderColor = "#003300";
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.Fill.Color = strBorderColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.Width = 0.75;
}
else if (loopCnt == 2)
{
string LineColor = "#F79646";
series_i.Border.LineStyle = eLineStyle.Dot;
////series_i.LineColor = LineColor.ConvertToColor();
////series_i.LineWidth = 2.0;
////series_i.Marker.Style = eMarkerStyle.Circle;
//////((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Style = eMarkerStyle.Dot;
////series_i.Marker.Size = 8;
string BGColor = "#ccffcc";
////series_i.Marker.Fill.Color = BGColor.ConvertToColor();
string strBorderColor = "#F79646";
////series_i.Marker.Border.Fill.Color = strBorderColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).LineColor = LineColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).LineWidth = 2.0;
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Style = eMarkerStyle.Circle;
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Size = 8;
//((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.LineCap
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Fill.Color = BGColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.Fill.Color = strBorderColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.Width = 0.75;
}
else if (loopCnt == 3)
{
string LineColor = "#c0504d";
series_i.Border.LineStyle = eLineStyle.LongDashDotDot;
////series_i.LineColor = LineColor.ConvertToColor();
////series_i.LineWidth = 2.0;
////series_i.Marker.Style = eMarkerStyle.Triangle;
//////((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Style = eMarkerStyle.Dot;
////series_i.Marker.Size = 8;
string BGColor = "#c0504d";
////series_i.Marker.Fill.Color = BGColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).LineColor = LineColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).LineWidth = 2.0;
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Style = eMarkerStyle.Triangle;
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Size = 8;
//((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.LineCap
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Fill.Color = BGColor.ConvertToColor();
string strBorderColor = "#003300";
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.Fill.Color = strBorderColor.ConvertToColor();
((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Border.Width = 0.75;
}
//else if (loopCnt == 4)
//{
// string LineColor = "#c0504d";
// series_i.Border.LineStyle = eLineStyle.LongDashDotDot;
// series_i.LineColor = LineColor.ConvertToColor();
// series_i.LineWidth = 1.5;
// series_i.Marker.Style = eMarkerStyle.Square;
// //((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Marker.Style = eMarkerStyle.Dot;
// series_i.Marker.Size = 8;
// string BGColor = "#c0504d";
// series_i.Marker.Fill.Color = BGColor.ConvertToColor();
//}
else
{
////series_i.LineColor = System.Drawing.Color.Aqua;
////series_i.LineWidth = 1.5;
////series_i.Marker.Style = eMarkerStyle.Circle;
////series_i.Marker.Size = 8;
////series_i.Marker.Fill.Color = System.Drawing.Color.Aqua;
}
//series_i.Smooth = eLineStyle.Dash;
//((OfficeOpenXml.Drawing.Chart.ExcelLineChartSerie)series_i).Series=eChartType.d
loopCnt++;
}
//var series_four = summary_Chart_four.Series.Add(myWorksheet_summary_data.Cells["C10:" + lastColumn_series1], myWorksheet_summary_data.Cells["C6:" + lastColumn_xaxis]);//working
//series_four.Header = myWorksheet_summary_data.Cells["A9"].Value.ToString();
//var series_four1 = summary_Chart_four.Series.Add(myWorksheet_summary_data.Cells["C14:" + lastColumn_series2], myWorksheet_summary_data.Cells["C6:" + lastColumn_xaxis]);
//series_four1.Header = myWorksheet_summary_data.Cells["A13"].Value.ToString();
summary_Chart_four.Border.Fill.Color = System.Drawing.Color.Black;
//summary_Chart_four.Title.Text = "Comparison of " + cVM.YearsBack + " Year Cumulative Total Return" + Environment.NewLine + " Assumes Initial Investment of $100" + Environment.NewLine + strMonth + " " + strSelectedDt.Year;
summary_Chart_four.Title.Text = "COMPARISON OF CUMULATIVE TOTAL RETURN";
summary_Chart_four.SetSize(960, 600);
// Add to 6th row and to the 6th column
summary_Chart_four.Legend.Font.Size = 10;
((OfficeOpenXml.Drawing.Chart.ExcelChartStandard)summary_Chart_four).Legend.Font.SetFromFont("Calibri", 11, false, false, false, false);
((OfficeOpenXml.Drawing.Chart.ExcelChartStandard)summary_Chart_four).YAxis.Font.SetFromFont("Arial", 10, false, false, false, false);
((OfficeOpenXml.Drawing.Chart.ExcelChartStandard)summary_Chart_four).XAxis.Font.SetFromFont("Arial", 10, false, false, false, false);
((OfficeOpenXml.Drawing.Chart.ExcelChartStandard)summary_Chart_four).Title.Font.Bold = true;
((OfficeOpenXml.Drawing.Chart.ExcelChartStandard)summary_Chart_four).Title.Font.SetFromFont("Calibri", 16, false, false, false, false);
//summary_Chart_four.Legend.Border.Fill.Color = System.Drawing.Color.Black;
summary_Chart_four.SetPosition(0, 0, 0, 0);
summary_Chart_four.XAxis.MajorTickMark = eAxisTickMark.In;
//summary_Chart.XAxis.MajorTickMark = eAxisTickMark.In;
summary_Chart_four.XAxis.MinorTickMark = eAxisTickMark.None;
summary_Chart_four.YAxis.MinorTickMark = eAxisTickMark.None;
summary_Chart_four.Legend.Position = eLegendPosition.Top;
summary_Chart_four.YAxis.CrossBetween = eCrossBetween.MidCat;
summary_Chart_four.XAxis.MajorGridlines.CompoundLineStyle = eCompundLineStyle.Double;

ASP.NET MVC : accesing object properties

I'm converting my code for specific models to a generic (all models will be accepted) version so I'm converting my label border but I can't access data in model because of I was accessing them like this:
worksheet.Cells["A" + index].Value = temp[i - 2].CarID.ToString();
but now I converted this access to something like this:
worksheet.Cells[L + index].Value = temp[i - 2].names[j].ToString();
but it's not working. I understand first one accesses object values but second one tries to access different one so how can I access this object values? I'm past full code for this function can you give me some idea about this situation? Thanks for help
public void EEPCreateExcelGeneric(ReportRange reportRange)
{
using (ExcelPackage excel = new ExcelPackage())
{
// var temp = db.Database.SqlQuery<CarsTrxViewModel>(SqlCars.CarsTrxByID()).ToList();
var temp = db.Cars.ToList();
Cars cars = new Cars();
// var properties = temp.GetType().GetProperties();
var names = new List<string>();
var properties = cars.GetType().GetProperties();
foreach (var item in properties)
{
var attribute = (DisplayNameAttribute)item.GetCustomAttribute(typeof(DisplayNameAttribute), true);
if (attribute != null)
{
names.Add(attribute.DisplayName);
}
else
{
names.Add(item.Name);
}
}
// System.Diagnostics.Debug.WriteLine(properties);
DateTime startdate = reportRange.StartDate;// ?? new DateTime(2000, 10, 10, 1, 1, 1, 1);
DateTime enddate = reportRange.EndDate;// ?? DateTime.Now;
DateTime now = DateTime.Now;
string date = now.ToShortDateString();
string time = now.ToLongTimeString();
date = date + "-" + time;
// modeli çekerken db de temizlersek çok daha hızlı olur
foreach (var item in temp.ToList())
{
if (item.CreateDate < startdate || item.CreateDate > enddate)
{
temp.Remove(item);
}
}
int RowRange = temp.Count();
string name = "Report_";
date = date.Replace(" ", "_");
date = date.Replace(",", "_");
date = date.Replace(":", "-");
date = date.Replace("/", "_");
string sonu = ".xls";
date += sonu;
name += date;
ExcelRecords m = new ExcelRecords();
m.IsExist = false;
m.CreateDate = now;
m.EndDate = enddate;
m.StartDate = startdate;
m.GuidName = name;
db.ExcelRecords.Add(m);
db.SaveChanges();
excel.Workbook.Worksheets.Add("Worksheet1");
var worksheet = excel.Workbook.Worksheets["worksheet1"];
//worksheet.Cells["A1"].Value = "CarID";
//worksheet.Cells["B1"].Value = "CarBrand";
//worksheet.Cells["C1"].Value = "CarModel";
//worksheet.Cells["D1"].Value = "CreateDate";
//worksheet.Cells["A1"].Style.Font.Bold = true;
//worksheet.Cells["B1"].Style.Font.Bold = true;
//worksheet.Cells["C1"].Style.Font.Bold = true;
//worksheet.Cells["D1"].Style.Font.Bold = true;
for (int i = 0; i < names.Count(); i++)
{
string L = (Convert.ToChar(65+i)).ToString();
L += "1";
System.Diagnostics.Debug.WriteLine(L);
worksheet.Cells[L].Value = names[i];
worksheet.Cells[L].Style.Font.Bold = true;
}
for (int i = 2; i < (RowRange + 2); i++)
{
/*
string L = (Convert.ToChar(63 + i)).ToString();
string index = i.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CarID.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CarBrand.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CarModel.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CreateDate.ToString();
*/
string index = i.ToString();
for (int j = 0; j < names.Count; j++)
{
string L = (Convert.ToChar(65 + j)).ToString();
worksheet.Cells[L + index].Value = temp[i - 2].names[j].ToString();//<=
// its not working what is right way for doing this
}
worksheet.Cells["A" + index].Value = temp[i - 2].CarID.ToString();
worksheet.Cells["B" + index].Value = temp[i - 2].CarBrand.ToString();
worksheet.Cells["C" + index].Value = temp[i - 2].CarModel.ToString();
worksheet.Cells["D" + index].Value = temp[i - 2].CreateDate.ToString();
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
string path = Path.Combine(Server.MapPath("~/"), ("Reports\\" + name));
FileInfo excelFile = new FileInfo(path);
excel.SaveAs(excelFile);
var bull = db.ExcelRecords.SingleOrDefault(b => b.GuidName == name);
if (bull != null)
{
bull.IsExist = true;
db.SaveChanges();
}
}
}

Formula not identify cell values

I'm generating an excel using the following code in my ASP.Net MVC Application
var fileName = DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
var outputDir = ConfigurationManager.AppSettings["ExcelUploadPath"];
// var fileName = "ExcellData.xlsx";
var file = new FileInfo(outputDir + fileName);
var fDate = JsonConvert.DeserializeObject<DateTime>(fromDate);
var tDate = JsonConvert.DeserializeObject<DateTime>(toDate);
using (var package = new OfficeOpenXml.ExcelPackage(file))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Plan " + DateTime.Now.ToShortDateString());
// --------- Data and styling goes here -------------- //
DataTable dt = planService.GetFlow(fDate, tDate, customerId, ordertypeId, suppliers, items);
if (dt != null)
{
int iCol = 1;
// Add column headings...
for (int i = 9; i < dt.Columns.Count; i++)
{
dt.Columns[i].ColumnName = dt.Columns[i].ColumnName.MultiInsert("/", 1, 3);
}
foreach (DataColumn c in dt.Columns)
{
worksheet.Cells[1, iCol].Value = c.ColumnName;
worksheet.Cells[1, iCol].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[1, iCol].Style.Font.Bold = true;
worksheet.Cells[1, iCol].Style.Fill.BackgroundColor.SetColor(Color.LightGray);
iCol++;
}
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
worksheet.Cells[j + 2, k + 1].Value = dt.Rows[j].ItemArray[k].ToString();
if (int.Parse(dt.Rows[j].ItemArray[7].ToString()) == 6)
{
worksheet.Cells[j + 2, k + 1].Style.Locked = false;
worksheet.Cells[j + 2, k + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[j + 2, k + 1].Style.Fill.BackgroundColor.SetColor(Color.Cyan);
}
if (int.Parse(dt.Rows[j].ItemArray[7].ToString()) == 7)
{
worksheet.Cells[j + 2, k + 1].Style.Locked = false;
worksheet.Cells[j + 2, k + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[j + 2, k + 1].Style.Fill.BackgroundColor.SetColor(Color.Magenta);
//worksheet.Cells[j + 2, k + 1].Formula =
if((k+1) > 10){
var addressList = new List<string>();
for (int i = 11; i <= k+1; i++)
{
addressList.Add(worksheet.Cells[((j + 2) -1) , i].Address);
}
var lstAdress = String.Join(",", addressList);
worksheet.Cells[j + 2, k + 1].Formula = "SUM(" + lstAdress + ")";
}
}
if (int.Parse(dt.Rows[j].ItemArray[7].ToString()) == 8)
{
//worksheet.Cells[j + 2, k + 1].Style.Locked = false;
worksheet.Cells[j + 2, k + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[j + 2, k + 1].Style.Fill.BackgroundColor.SetColor(Color.Gray);
}
}
var colCount = dt.Columns.Count;
// worksheet.Cells[j+2, 8, j+2, colCount- 1].Style.Numberformat.Format = "0.000";
var range = worksheet.Cells[j + 2, 9, j + 2, colCount - 1];
var r = range.ToString();
var decimalValidation = worksheet.DataValidations.AddDecimalValidation(range.ToString());
decimalValidation.ShowErrorMessage = true;
decimalValidation.ErrorStyle = ExcelDataValidationWarningStyle.stop;
decimalValidation.ErrorTitle = "The value you entered is not valid";
decimalValidation.Error = "This cell must be a valid positive number.";
decimalValidation.Operator = ExcelDataValidationOperator.greaterThanOrEqual;
decimalValidation.Formula.Value = 0D;
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
worksheet.Column(1).Hidden = true;
worksheet.Column(2).Hidden = true;
worksheet.Column(3).Hidden = true;
worksheet.Column(4).Hidden = true;
worksheet.Column(5).Hidden = true;
worksheet.Column(8).Hidden = true;
worksheet.Column(9).Hidden = true;
worksheet.Column(10).Hidden = true;
worksheet.Protection.IsProtected = true;
// save our new workbook and we are done!
worksheet.Calculate();
package.Save();
return Json(fileName, JsonRequestBehavior.AllowGet);
}
else
{
return Json("NoData", JsonRequestBehavior.AllowGet);
}
}
return Json("", JsonRequestBehavior.AllowGet);
Here I'm setting my formula with comma separated cell names eg:
SUM(A1,A2,A3.. etc)
The excel file is generating correctly. But the problem is the formula calculation is not happen when I open my excel file.
The formula works when I manually change a cell value in Column Type Agreed Flow.
And it can only identify values of manually edited cells.
How can I resolve this?
Formula recalculation is both an Excel and a workbook setting.
You could set it with at the workbook level with
workbook.CalcMode = ExcelCalcMode.Automatic;
If the user has set it to manual though, the formulas won't be recalculated.
If you want to ensure the saved values are correct you can force the calculation by calling
worksheet.Calculate();
You can also calculate the formulas at the workbook or range level, eg :
worksheet.Cells[j + 2, k + 1].Calculate();
or
package.Workbook.Calculate();
This is explained in the documentation. Keep in mind that EPPlus doesn't contain Excel's formula engine. It uses its own engine to parse and calculate formulas. Some things aren't supported
It worked when I change my formula as follows..
var addressList = new List<string>();
for (int i = 11; i <= k+1; i++)
{
addressList.Add(worksheet.Cells[((j + 2) -1) , i].Address);
}
var lstAdress = String.Join("+", addressList);
worksheet.Cells[j + 2, k + 1].Formula = "(" + lstAdress + ")";
I think there is an issue in my excel sheet when I use the SUM function So I write the formula without using it. Then it worked
(A1+B1+C1+D1+ ..... etc)

Repeat Heading to table in pdf

I am using the Itextsharp PDF tool to generate PDF using asp.net and C# , In that in one PDFPtable the last row data is repeating on next page means part of a table forwarded to next page. so want to show header for that Table on next page.
This is my code.
Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 20, 10);
string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf" + Guid.NewGuid().ToString("N") + ".pdf";
try
{
//Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
FileStream fs = new FileStream(pdfFilePath, FileMode.Create);
//
PdfWriter wri = PdfWriter.GetInstance(doc, fs);
//Header Section
string strImagePath = Server.MapPath("Images");
string strReportName = oReportDTO.strReportName + " " + oReportDTO.oDateRange.FromDate.ToString(DateFormat);
Chunk headerchunk = new Chunk(strReportName, new Font(1, 8.0f));
HeaderFooter oHeader = new HeaderFooter(new Phrase(headerchunk), false);
oHeader.Border = Rectangle.NO_BORDER;
oHeader.Alignment = 1;
doc.Header = oHeader;
//Footer Section
string name ="Logged in as : " +currentLoggedInUser.UserName + new string(' ',70)+ "Page Number : " + doc.PageNumber;
Chunk Footerchunk1 = new Chunk(name, new Font(1, 5.0f));
HeaderFooter oFooter1 = new HeaderFooter(new Phrase(Footerchunk1), true);
oFooter1.Border = Rectangle.NO_BORDER;
oFooter1.Alignment = 1;
doc.Footer = oFooter1;
iTextSharp.text.Image imgFooter = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromFile(strImagePath + "/TransRisk Logo168x97.png"), System.Drawing.Imaging.ImageFormat.Jpeg);
imgFooter.ScaleAbsolute(80, 50);
Chunk footerchunk = new Chunk(imgFooter, 260.0f, 0.0f);
HeaderFooter oFooter = new HeaderFooter(new Phrase(name),new Phrase(footerchunk));
oFooter.Border =Rectangle.NO_BORDER;
doc.Footer = oFooter;
doc.Open();//Open Document to write
Font font8 = FontFactory.GetFont("ARIAL", 7);
HtmlTable dt = customMatrixReport;
if (dt.Rows.Count > 0)
{
//Craete instance of the pdf table and set the number of column in that table
int startColumnPosition = 1;
int endColumnPosition = 13;//End Column number in Pdf Page
int NoOfReports = Convert.ToInt32(Math.Ceiling((decimal)(dt.Rows[0].Cells.Count - 1) / endColumnPosition));//Count How many Pages to show
int pageRowCount = 0;
List<PdfPCell> lstHeaderCells = new List<PdfPCell>();
PdfPTable oPdfTable = null;
PdfPCell oPdfPCell = null;
for (int report = 1; report <= NoOfReports; ++report)
{
doc.Add(oHeader);
//ColumnText.ShowTextAligned(
int noOfColumns = -1;
if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); }
else
{
oPdfTable = new PdfPTable(14);
//Widths Count
noOfColumns = 14;
}
oPdfTable.TotalWidth = 650f;
List<float> lstwidths = new List<float>();
lstwidths.Add(100f);
for (int i = 2; i <= noOfColumns; ++i)
{
lstwidths.Add(80f);
}
oPdfTable.SetTotalWidth(lstwidths.ToArray());
pageRowCount = 0;
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
//PageRowCount
pageRowCount = pageRowCount + 1;
//Description celll
if (rows == 0 )
{
//Background color for table header
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[0].InnerText, new Font(1, 8.0f, 1, Color.WHITE))));
oPdfPCell.BackgroundColor = new Color(118, 147, 199);
oPdfTable.AddCell(oPdfPCell);
}
else
{
//background color for Table cells
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[0].InnerText,new Font(1, 8.0f))));
oPdfPCell.BackgroundColor = new Color(232, 237, 255);
oPdfTable.AddCell(oPdfPCell);
}
//for header cel
if (rows == 0)
{
lstHeaderCells.Add(oPdfPCell);
}
for (int column = startColumnPosition; column <= endColumnPosition; column++)
{
if (rows == 0)
{
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[column].InnerText, new Font(1, 8.0f, 1, Color.WHITE))));
oPdfPCell.BackgroundColor = new Color(118, 147, 199);
oPdfTable.AddCell(oPdfPCell);
}
else
{
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[column].InnerText, new Font(1, 8.0f))));
oPdfPCell.BackgroundColor = new Color(232, 237, 255);
oPdfPCell.Column.Alignment = 2;
oPdfTable.AddCell(oPdfPCell);
}
if (rows == 0)
{
lstHeaderCells.Add(oPdfPCell);
}
}
if (pageRowCount >= 40 && rows != (dt.Rows.Count - 1))
{
pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
}
}
startColumnPosition = endColumnPosition + 1;
endColumnPosition = endColumnPosition + 13;
oPdfTable.SpacingBefore = 10;
oPdfTable.SpacingAfter = 10;
doc.Add(oPdfTable);
//doc.NewPage();
}
}
else
doc.Add(oHeader);
}
finally
{
doc.Close();
}
help me..
Change this line-
if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); }
To this-
if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); oPdfTable.HeaderRows = 1;}
After this line-
oPdfTable = new PdfPTable(14);
Add this-
oPdfTable.HeaderRows = 1;
Change this line-
pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
To this-
pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.HeaderRows = 1; oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }

how to set large table on next pages if contain is large with iTextSharp

I've added an header and a footer on my document by PdfPageEventHelper.
The document has several "large" tables populated at runtime.
I've tried to add those tables simply by "documen.Add(table)", but my header and my footer results overwritten.
I've already tried both methods to add the tables (WriteSelectedRows and document.Add(myPdfPtable).
Here is the code of the PageEventHelper for Head:
public override void OnEndPage(PdfWriter writer, Document doc)
{
Phrase phrase = null;
PdfPCell cell = null;
PdfPTable maintable = new PdfPTable(2);
maintable.TotalWidth = 500f;
maintable.LockedWidth = true;
maintable.SetWidths(new float[] { 50f, 400f });
#region checklogo
if (IsLogo!=0)
{
// code for display head like logo, etc
}
#endregion CheckSchoolNameandAddress
maintable.WriteSelectedRows(0, -1, 50, 835, writer.DirectContent);
Color color = new Color(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
DrawLine(writer, 25f, 780f, doc.PageSize.Width - 25f, 780f,color);
DrawLine(writer, 25f, 780f, doc.PageSize.Width - 25f, 780f, color);
}
Here is the code of the PageEventHelper for footer:
public override void OnEndPage(PdfWriter writer, Document doc)
{
Phrase phrase = null;
PdfPCell cell = null;
PdfPCell cell1 = null;
PdfPCell cell2 = null;
int pageN = writer.PageNumber;
String text = "Page " + pageN;
PdfPTable foootertable = new PdfPTable(3);
foootertable.TotalWidth = 500f;
foootertable.LockedWidth = true;
foootertable.SetWidths(new float[] { 50f, 60f, 50f });
#region checkprintedbyReportNamePageNo
if (Isfooter != 0)
{
// code for footer like pageno, etc
}
#endregion CheckprintedbyReportNamePageNo
foootertable.WriteSelectedRows(0, -1, 30,30, writer.DirectContent);
color = new Color(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
DrawLine(writer, 25f, 32f, doc.PageSize.Width - 25f, 32f, color);
DrawLine(writer, 25f, 32f, doc.PageSize.Width - 25f, 32f, color);
}
Table code which display on all page like reportdiaplay
public ActionResult DetailReportPDF(int TempId, int ReportModuleId, string BoardStageId, string ShiftId, string ClassDivisionId, string Subjects)
{
try
{
var BaseUrl = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
IBoard board = Session["SchoolAdmin"] as IBoard;
if (board != null)
{
int yearid = 0; IYears currentyear = YearsDomain.GetCurrentYears(board.Board_Id); if (currentyear != null) yearid = currentyear.Year_Id;
string SchoolAddress = "";
string SchoolName = "";
string SchoolLogo = "";
SchoolName = board.Board_Name != null ? board.Board_Name.ToUpper() : "";
SchoolAddress = (board.Board_Address1 != null ? board.Board_Address1.ToUpper() + "," : "") + (board.Board_City != null ? board.Board_City + "," : "") + (board.Board_State != null ? board.Board_State + ", " : "") + (board.Board_Country != null ? board.Board_Country + " - " : "") + (board.Board_Pincode != null ? board.Board_Pincode + "." : "");
SchoolLogo = Session["SchoolLogo"] != null ? Session["SchoolLogo"].ToString() : "";
string filename = "";
DateTime now = DateTime.Now;
Document document = new Document(PageSize.A4);
document.SetMargins(88, 88, 80, 10f);
iTextSharp.text.Font NormalFont = FontFactory.GetFont("Arial Unicode MS,Arial", 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
iTextSharp.text.Font VNormalFont = FontFactory.GetFont("Arial Unicode MS,Arial", 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
iTextSharp.text.Font LARGFont = FontFactory.GetFont("Arial Unicode MS,Arial", 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
Phrase phrase = null;
PdfPCell cell = null;
PdfPTable maintable = null;
PdfPTable table = null;
PdfPTable secondTable = null;
PdfPCell TableCell = new PdfPCell();
PdfPCell secondTableCell = new PdfPCell();
secondTableCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
iTextSharp.text.Color color = null;
document.Open();
List<ReportSetLayout> lst = new List<ReportSetLayout>();
IReportTemplate RTD = ReportTemplateDomain.GetReportTemplateFromId(TempId);
string Newstr = "";
int IsLogo = 0;
string LogoSize="";
string LogoPosition="";
int IsSchoolName=0;
int IsSchoolAddress=0;
string SchoolNameSize = "";
string SchoolNamePosition = "";
string SchoolAddressSize = "";
string SchoolAddressPosition = "";
int Isfooter = 0;
int IsPrintedBy =0;
int IsReportName =0;
int PageNo =0;
string ShowPrintedBy="";
string ShowReportName ="";
string ShowPageNo = "";
IReportModule ReportModule = ReportModuleDomain.GetReportModulesFromId(ReportModuleId);
IBoardUserRights boarduserrights = BoardUserRightsDomain.GetBoardUserRights(board.Board_Id, "Reports", Session["BoardUserName"].ToString());
IBoardUser BU = BoardUserDomain.getBoardUserById(Convert.ToInt32(boarduserrights.Board_User_Id));
if (RTD != null)
{
#region forLogo
// code for get value for header logo
#endregion forLogo
#region forschoolName&address
// code for get value for header address
#endregion forschoolName&address
#region forprintedbyReportNamePageNo
// code for get value for footer
#endregion forprintedbyReportNamePageNo
}
writer.PageEvent = new Header() { SName = SchoolName, SAddress = SchoolAddress, SLogo = SchoolLogo, IsLogo=IsLogo, LogoSize = LogoSize, LogoPosition = LogoPosition ,IsSchoolName=IsSchoolName , IsSchoolAddress=IsSchoolAddress, SchoolNameSize=SchoolNameSize ,SchoolNamePosition=SchoolNamePosition,SchoolAddressSize=SchoolAddressSize,SchoolAddressPosition=SchoolAddressPosition};
// writer.PageEvent = new Header();
writer.PageEvent = new Footer(){ Isfooter=Isfooter,IsPrintedBy=IsPrintedBy,IsReportName=IsReportName,IsPageNo=PageNo,PrintedBy=ShowPrintedBy,ReportName=ShowReportName};
#region ReportBind
string Shortby = "";
List<string> lstformat = new List<string>();
List<string> lstWrap = new List<string>();
List<ReportColumnDetails> lstReportColumn = new List<ReportColumnDetails>();
lstReportColumn = ReportColumnDomain.GetReportColumnsFromReportModule(ReportModuleId);
List<IReportTemplateColumn> lstRptempcol = new List<IReportTemplateColumn>();
lstRptempcol = ReportTemplateColumnDomain.GetAllReportTemplateColumnbyID(TempId);
List<int> colindexid = new List<int>();
List<int> ColWidth = new List<int>();
foreach (var col in lstRptempcol)
{
ColWidth.Add(Convert.ToInt32(col.ColumnWidth));
colindexid.Add(Convert.ToInt32(col.Column_Index_Id));
}
foreach (var shortName in lstRptempcol)
{
if (shortName.Sortby == Convert.ToByte(1))
{
Shortby = lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault();
}
if (lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault().Contains("Date"))
{
lstformat.Add(lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault() + "_" + shortName.Format);
}
if (lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault().Contains("Gender"))
{
lstformat.Add(lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault() + "_" + shortName.Format);
}
if (shortName.Wrap == Convert.ToByte(1))
{
lstWrap.Add(lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault());
}
}
//string[] cols = Columns.TrimEnd(',').Split(',');
//string[] colsindex = ColumnsIndex.TrimEnd(',').Split(',');
string str = "";
string str1 = "";
// DataTable dt = new DataTable("ReportTable");
if (ReportModule != null)
{
if (ReportModule.Report_Module_Name == "Teacher")
{
var items = new List<int>(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 });
string H1 = "Sr.No", H2 = "Teacher Name", H3 = "Contact No", H4 = "Address", H5 = "Gender", H6 = "Marital Status", H7 = "Join Date", H8 = "Leave Date", H9 = "Physically Challenged ", H10 = "Photo", H11 = "EmailId", H12 = "EmployeeId", H13 = "Group", H14 = "Religion", H15 = "Cast Category", H16 = "Cast", H17 = "Designation", H18 = "Service Category", H19 = "Anniversary Date", H20 = "Education";
#region trimdata
List<int> lstBoardStageId = new List<int>();
if (BoardStageId != "" || BoardStageId != null)
{
string[] BSId = BoardStageId.TrimEnd(',').Split(',');
for (int i = 0; i <= BSId.Count() - 1; i++)
{
if (BSId[i] != "")
lstBoardStageId.Add(Convert.ToInt32(BSId[i]));
}
}
List<int> lstShiftId = new List<int>();
if (ShiftId != "" || ShiftId != null)
{
string[] ShiftIDs = ShiftId.TrimEnd(',').Split(',');
for (int i = 0; i <= ShiftIDs.Count() - 1; i++)
{
if (ShiftIDs[i] != "")
lstShiftId.Add(Convert.ToInt32(ShiftIDs[i]));
}
}
List<int> lstClassDivisionId = new List<int>();
if (ClassDivisionId != "" || ClassDivisionId != null)
{
string[] classDiv = ClassDivisionId.TrimEnd(',').Split(',');
for (int i = 0; i <= classDiv.Count() - 1; i++)
{
if (classDiv[i] != "")
lstClassDivisionId.Add(Convert.ToInt32(classDiv[i]));
}
}
List<int> lstSubjects = new List<int>();
//if (Subjects != "" || Subjects != null)
//{
string[] subjs = Subjects.TrimEnd(',').Split(',');
for (int i = 0; i <= subjs.Count() - 1; i++)
{
if (subjs[i] != "")
lstSubjects.Add(Convert.ToInt32(subjs[i]));
}
//}
#endregion trimdata
List<ReportTecaherDetails> resultTeacher = new List<ReportTecaherDetails>();
resultTeacher = TeacherDomain.GetReportTeacher1(board.Board_Id, lstBoardStageId, lstShiftId, lstSubjects, lstClassDivisionId, Shortby, lstformat, yearid);
float[] widthArry = new float[20];
float widthCount = 0;
for (int i = 0; i < ColWidth.Count; i++)
{
widthArry[i] = ColWidth[i];
widthCount += ColWidth[i];
}
widthArry = widthArry.Where(x => x != 0).ToArray();
table = new PdfPTable(widthArry);
table.TotalWidth = 550f;
table.LockedWidth = true;
table.SetWidths(widthArry);
#region CheckHeaderText
foreach (var HeaderText in lstRptempcol)
{
//code for headerText
}
#endregion CheckHeaderText
int Srno = 1;
int count = 0;
for (int a = 0; a < colindexid.Count; a = a + 1)
{
if (colindexid.Contains(Convert.ToInt32(a.ToString())))
{
#region addcolumnHeadeName
if (a.ToString() == Convert.ToString(0))
{
// dt.Columns.Add(new DataColumn(H1, typeof(string)));
phrase = new Phrase();
phrase.Add(new Chunk(H1, FontFactory.GetFont("Arial Unicode MS,Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
cell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
cell.BorderColor = new iTextSharp.text.Color(229, 229, 229);
cell.FixedHeight = 10f;
table.AddCell(cell);
}
else if (a.ToString() == Convert.ToString(1))
{
// dt.Columns.Add(new DataColumn(H1, typeof(string)));
phrase = new Phrase();
phrase.Add(new Chunk(H2, FontFactory.GetFont("Arial Unicode MS,Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
cell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
cell.BorderColor = new iTextSharp.text.Color(229, 229, 229);
cell.FixedHeight = 10f;
table.AddCell(cell);
}
// .... else if{} same as above
#endregion addcolumnHeadeName
}
}
document.Add(table);
secondTable = new PdfPTable(widthArry);
secondTable.TotalWidth = 550f;
secondTable.LockedWidth = true;
secondTable.SetWidths(widthArry);
foreach (var item in resultTeacher)
{
#region rowadd
if (colindexid.Contains(Convert.ToInt32(0)))
{
phrase = new Phrase();
phrase.Add(new Chunk(Convert.ToString(Srno), FontFactory.GetFont("Arial Unicode MS,Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
secondTableCell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
secondTableCell.BorderColor = new iTextSharp.text.Color(229, 229, 229);
secondTableCell.FixedHeight = 50f;
secondTable.AddCell(secondTableCell);
}
else
{
}
// .... if{} same as above
#endregion rowadd
Srno++;
}
document.Add(secondTable);
}
}
#endregion ReportBind
filename = filename + now.Hour.ToString("00") + now.Minute.ToString("00") + now.Second.ToString("00") + now.Millisecond.ToString() + now.DayOfYear.ToString("000") + now.Day.ToString("00") + now.Month.ToString("00") + now.Year.ToString("0000") + ".pdf";
document.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
Response.Close();
}
return View();
}
else
{
return Redirect(BaseUrl);
}
}
catch (Exception ex)
{
throw ex;
}
}
You Can try
Image.ScaleToFitLineWhenOverflow = false;
Refer SO Answer # Set Pagination in Itextsharp Table

Categories

Resources