I'm using asp.net MVC 4 and epplus as a nuget package for exporting my data into an excel file. I do that as the following:
var excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add("Consumption");
workSheet.View.RightToLeft = true;
for (var col = 1; col <= totalCols; col++)
{
workSheet.Cells[1, col].Style.Font.Name = "B Zar";
workSheet.Cells[1, col].Style.Font.Size = 16;
workSheet.Cells[1, col].Style.Font.Bold = true;
workSheet.Cells[1, col].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
workSheet.Cells[1, col].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
workSheet.Cells[1, col].Value = ds.Tables[0].Columns[col - 1].ColumnName;
}
for (var row = 1; row <= totalRows; row++)
for (var col = 0; col < totalCols; col++)
{
workSheet.Cells[row + 1, col + 1].Style.Font.Name = "B Zar";
workSheet.Cells[row + 1, col + 1].Style.Font.Size = 11;
workSheet.Cells[row + 1, col + 1].Value = ds.Tables[0].Rows[row - 1][col];
}
workSheet.Cells[1, 1, totalRows + 1, totalCols].Style.Border.Top.Style =
workSheet.Cells[1, 1, totalRows + 1, totalCols].Style.Border.Bottom.Style =
workSheet.Cells[1, 1, totalRows + 1, totalCols].Style.Border.Right.Style =
workSheet.Cells[1, 1, totalRows + 1, totalCols].Style.Border.Left.Style =
OfficeOpenXml.Style.ExcelBorderStyle.Thin;
workSheet.Cells[1, 1, totalRows + 1, totalCols].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=Consumptions.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
The problem is that when I download the file and open it on Excel 2016, the font family not affected but on the font name box, it appears. If I focus on the combo box and press Enter, the font family will be affected.
How can I solve this problem?
Try this:
var allCells = sheet.Cells[1, 1, sheet.Dimension.End.Row, sheet.Dimension.End.Column];
var cellFont = allCells.Style.Font;
cellFont.SetFromFont(new Font("Times New Roman", 12));
cellFont.Bold = true;
cellFont.Italic = true;
workSheet.Cells.Style.Font.Name = "Arial Narrow";
workSheet.Cells.Style.Font.Size = 10;
This will affect all rows and columns.
This issue occurs because EPPlus (version 4.5.3.2) does not support Font Charset.
Font Charset for the selected Font ('B Zar') is ARABIC (=178).
I have forked the EPPlus on the url https://github.com/mzatkhahi/EPPlus and fixed this bug.
Then you can use this code to support the persian font:
workSheet.Cells[1, col].Style.Font.Charset = 178;
//For specific cell range
using (var range = worksheet.Cells[From Row, From Column, To Row, To Column])
{
range.Style.Font.Bold = true;
}
//For understanding,
//Column Number = Worksheet.Dimension.End.Column
//Row Number = Worksheet.Dimension.End.Row
// OR
//For Whole row
using(var package = new OfficeOpenXml.ExcelPackage())
{
worksheet.Row(5).CustomHeight = false;
worksheet.Row(5).Height = 50;
worksheet.Row(5).Style.Font.Bold = true ;
worksheet.Row(5).Style.WrapText = true;
}
Related
I am trying to create a pdf in the attached format by using grouping using c#. The first page is fine but next page still first-page first column name exists. while creating a pdf new page get the first page data
I used
DeleteBodyRows()
for removing table rows but still the same :
foreach (DataRow row in dataTable.Rows)
{
//write in new row
var datatable = dataTable;
var departments = from r in datatable.Rows.OfType<DataRow>()
group r by r["emp_reader_id"] into g
select new { emp_reader_id = g.Key, Data = g };
foreach (var department in departments)
{
foreach (var roww in department.Data)
{
iii++;
if (ii == 0)
{
PdfPCell cell1333 = new PdfPCell(new iTextSharp.text.Phrase("Name " + ":" + roww.ItemArray[1].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 19, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
cell1333.Colspan = 8;
cell1333.Border = 0;
cell1333.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
table.AddCell(cell1333);
PdfPCell cell1 = new PdfPCell(new iTextSharp.text.Phrase("E.Code " + ":" + roww.ItemArray[2].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 19, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
cell1.Colspan = 8;
cell1.Border = 0;
cell1.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
table.AddCell(cell1);
PdfPCell cell144 = new PdfPCell(new iTextSharp.text.Phrase("Department " + ":" + roww.ItemArray[4].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 19, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
cell144.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
cell144.Colspan = 8;
cell144.Border = 0;
cell144.Border = iTextSharp.text.Rectangle.NO_BORDER;
table.AddCell(cell144);
PdfPCell cell155 = new PdfPCell(new iTextSharp.text.Phrase("Designation " + ":" + roww.ItemArray[5].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 19, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
cell155.Colspan = 8;
cell155.Border = 0;
cell155.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
cell155.Border = iTextSharp.text.Rectangle.NO_BORDER;
table.AddCell(cell155);
PdfPCell cell166 = new PdfPCell(new iTextSharp.text.Phrase("Name Of Facility " + ":" + roww.ItemArray[6].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 19, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
cell166.Colspan = 8;
cell166.Border = 0;
cell166.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
cell166.Border = iTextSharp.text.Rectangle.NO_BORDER;
table.AddCell(cell166);
DataTable dtp1 = new DataTable();
dtp1.Columns.Add("Date", typeof(string));
dtp1.Columns.Add("F1", typeof(string));
dtp1.Columns.Add("F2", typeof(string));
dtp1.Columns.Add("F3", typeof(string));
dtp1.Columns.Add("F4", typeof(string));
dtp1.Columns.Add("Hours", typeof(string));
dtp1.Columns.Add("Remarks", typeof(string));
for (int i = 0; i < 7; i++)
{
PdfPCell cell = new PdfPCell(new iTextSharp.text.Phrase(dtp.Columns[i].ColumnName, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 19, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.ITALIC, iTextSharp.text.Color.WHITE)));
cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#2980b9"));
cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
table.AddCell(cell);
}
}
ii++;
DateTime date = DateTime.Parse(roww.ItemArray[3].ToString(), System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
string strDate = String.Format("{0:dd/MM/yyyy}", date);
PdfPCell cell19 = new PdfPCell(new iTextSharp.text.Phrase(strDate, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK)));
cell19.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
table.AddCell(cell19);
table.AddCell(string.Empty);
table.AddCell(string.Empty);
table.AddCell(string.Empty);
table.AddCell(string.Empty);
table.AddCell(string.Empty);
table.AddCell(string.Empty);
}
ii = 0;
pdfDoc.Add(table);
table.DeleteBodyRows();
pdfDoc.NewPage();
}
break;
}
All new page contains the first page's first row continuously. Above is the code I tried.
Any help ?
Thanks!
add below line next to table.DeleteBodyRows()
To remove first row
table.DeleteRow(0);
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)
I am upgrading .xls download in .aspx page to .xlsx download using c# EppPlus. How can I add Alternative row background color like each other row has gray background ?
I am using the below code
public void DumpExcel(DataTable tbl)
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
ws.Cells["A1"].LoadFromDataTable(tbl, true);
using (ExcelRange rng = ws.Cells["A1:AA1"])
{
rng.Style.Font.Bold = false;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 51, 153)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
rng.Style.Font.Size = 10;
}
// Add Word wrap
for (int i = 1; i <= tbl.Columns.Count; i++)
{
ws.Column(i).AutoFit();
ws.Column(i).Width = 20;
ws.Column(i).Style.WrapText = true;
ws.Column(i).Style.VerticalAlignment = ExcelVerticalAlignment.Top;
ws.Column(i).Style.Font.Size = 9;
}
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=UserEntitleDLX.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
}
I think it should also be mentioned that there is an overload for LoadFromDataTable where you can pass a TableStyle like so
ws.Cells["A1"].LoadFromDataTable(tbl, true, TableStyles.Dark1);
If you want the tbl's area to be formatted from scratch then you could do something like this
for (var row = 1; row <= tbl.Rows.Count; row++)
{
for (var column = 1; column <= tbl.Columns; column++)
{
ws.Cells[row, column].Style.Font.Bold = false;
ws.Cells[row, column].Style.Fill.PatternType = ExcelFillStyle.Solid;
ws.Cells[row, column].Style.Font.Size = 10;
ws.Cells[row, column].Style.Fill.BackgroundColor.SetColor(column%2 == 0
? Color.Blue
: Color.Gray);
}
}
Below piece of code did the job for me
for (int row = ws.Dimension.Start.Row; row <= ws.Dimension.End.Row; row++)
{
int pos = row % 2;
ExcelRow rowRange = ws.Row(row);
ExcelFill RowFill = rowRange.Style.Fill;
RowFill.PatternType = ExcelFillStyle.Solid;
switch (pos)
{
case 0:
RowFill.BackgroundColor.SetColor(System.Drawing.Color.White);
break;
case 1:
RowFill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
break;
}
}
Here's a variation of the given answers I use (as extension). My requirements required a subset of columns be colored, not the whole row, and with more than just two colors.
public static void ApplyBackgroundColorsPerRow(
this ExcelWorksheet worksheet,
int startRow, int startColumn, int endRow, int endColumn,
List<System.Drawing.Color> colors)
{
if (startRow <= endRow)
{
int numberOfColors = colors.Count;
for (int row = startRow; row <= endRow; row++)
{
using (ExcelRange range = worksheet.Cells[row, startColumn, row, endColumn])
{
range.Style.Fill.PatternType = ExcelFillStyle.Solid;
range.Style.Fill.BackgroundColor.SetColor(colors[(row - startRow) % numberOfColors]);
}
}
}
}
Alternating white / gray (light gray is my recommendation over grey) would look like this:
worksheet.ApplyBackgroundColorsPerRow(
startRow: 1,
startColumn: 1,
endRow: 20,
endColumn: 5,
colors: new List<System.Drawing.Color>()
{
System.Drawing.Color.White,
System.Drawing.Color.LightGray
}
);
I am using Microsoft.Office.Interop.Excel library.
I have a cell with values "Green Red". What I want is pretty simple. I want to insert "Green" text to be green and "Red" to be red, like that:
I am using this code to insert data in cell:
Excel.Application excelApp = new Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Excel._Worksheet workSheet = excelApp.ActiveSheet;
for (int startIndex = 0; startIndex < 10; startIndex++)
{
workSheet.Cells[1, (startIndex + 1)] ="Green" + " Red";
}
How to do it?
I've tried this approach, but I do not know what [RangeObject] is:
[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
Try:
workSheet.Cells[1, (i + 1)].Characters[start_pos, len].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
where start_pos and len is the part of the string where to apply color.
Your use case example:
Application excelApp = new Application();
excelApp.Workbooks.Add();
// single worksheet
_Worksheet workSheet = excelApp.ActiveSheet;
string Green = "Green";
string Red = "Red";
for (int start = 0; start < 10; start++)
{
Range ColorMeMine = workSheet.Cells[1, (start + 1)];
ColorMeMine.Value = string.Format("{0} {1}", Green, Red);
ColorMeMine.Characters[0, Green.Length].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
ColorMeMine.Characters[Green.Length + 1, Green.Length + 1 + Red.Length].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
}
I'm using following method to create and position the excel chart beside table data. below code is working fine, but chart position(height) is creating problem when number of charts increase.
There is any solution for draw chart with cell value? or other thing that may be used by me to keep chart beside table data.
I want to print result of following method page by page and therefore want to place it correctly.
below is my code:
Excel.Application xla = new Excel.Application();
int height=75;
string uppercell = "B12";
int cell = 12;
if (CheckBox1.Checked == true)
{
string table_name, chart_name;
table_name = "Ration Table";
chart_name = "Ratio";
string st = "";
con.Open();
trying(ws, st, height, uppercell, cell, table_name, chart_name);
con.Close();
cell = cell + 33;
uppercell = "B" + cell;
height = 496 + 75;//height + 300;
}
public void trying(Excel.Worksheet ws,string st,double height,string uppercell,int cell,string table_name,string chart_name)
{
MySqlDataAdapter da = new MySqlDataAdapter(st, con);
System.Data.DataTable dtMainSQLData = new System.Data.DataTable();
da.Fill(dtMainSQLData);
DataColumnCollection dcCollection = dtMainSQLData.Columns;
//int cell = System.Int32.Parse(uppercell.Substring(1));
//********************** Now create the chart. *****************************
Excel.ChartObjects chartObjs = (Excel.ChartObjects)ws.ChartObjects(Type.Missing);
//Excel.ChartObject chartObj = chartObjs.Add(left, top, width, height);
Excel.ChartObject chartObj = chartObjs.Add(260, height, 350, 210);
Excel.Chart xlChart = chartObj.Chart;
//ws.Shapes.Item("xlChart").Top = (float)(double)ws.get_Range("E6").Top;//this.Controls.AddChart(this.Range["D2", "H12"]"chart1");
int nRows = dtMainSQLData.Rows.Count;
int nColumns = dtMainSQLData.Columns.Count;
string upperLeftCell = uppercell;// "B10";
int endRowNumber = System.Int32.Parse(upperLeftCell.Substring(1)) + nRows - 1;
char endColumnLetter = System.Convert.ToChar(Convert.ToInt32(upperLeftCell[0]) + nColumns - 1);
string upperRightCell = System.String.Format("{0}{1}", endColumnLetter, System.Int32.Parse(upperLeftCell.Substring(1)));
string lowerRightCell = System.String.Format("{0}{1}", endColumnLetter, endRowNumber);
Excel.Range rg = ws.get_Range(upperLeftCell, lowerRightCell);
for (int i = cell - 1; i < dtMainSQLData.Rows.Count + cell; i++)
{
for (int j = 2; j < dtMainSQLData.Columns.Count + 2; j++)
{
if (i == cell - 1)
{
xla.Cells[i, j] = dcCollection[j - 2].ToString();
}
else
{
xla.Cells[i, j] = dtMainSQLData.Rows[i - cell][j - 2].ToString();
}
}
}
//ws.Columns.AutoFit();
//for (int i = 1; i <= dtMainSQLData.Rows.Count; i++)
//{
// rg[1, i] = dtMainSQLData.Rows[i - 1][0].ToString(); //For Adding Header Text
// rg[2, i] = int.Parse(dtMainSQLData.Rows[i - 1][1].ToString()); //For Adding Datarow Value
//}
int lcellh = cell - 10;
int rcellh = cell - 10;
string lcellh1 = "B" + lcellh;
string rcellh1 = "L" + rcellh;
//-----------------------for company name and address-------------------------//
Excel.Range chartRange3;
ws.get_Range(lcellh1, rcellh1).Merge(false);//----------------------------------upperleft_cell, lowerright_cell
chartRange3 = ws.get_Range(lcellh1, rcellh1);
chartRange3.FormulaR1C1 = "BLUE BIRD FOODS (I) PVT.LTD.";//----------------------------------company name
chartRange3.HorizontalAlignment = 3;
chartRange3.VerticalAlignment = 3;
chartRange3.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
chartRange3.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.PaleVioletRed);
chartRange3.Font.Size = 20;
Excel.Range formatRange3;
formatRange3 = ws.get_Range(lcellh1, rcellh1);//----------------------------------hrow_border1, hrow_border2
formatRange3.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
//------for making header font bold
int hcell = cell - 1;
string hleftrange = "B" + hcell;
string hrightrange = "D" + hcell;
Excel.Range formatRange1;
formatRange1 = ws.get_Range(hleftrange);//----------------------------------hrow_bold
formatRange1.EntireRow.Font.Bold = true;
formatRange1.HorizontalAlignment = 3;
formatRange1.VerticalAlignment = 3;
//ws.Cells[1, 3] = "Bold";
//-------for giving broder to header
Excel.Range formatRange2;
formatRange2 = ws.get_Range(hleftrange, hrightrange);//----------------------------------hrow_border1, hrow_border2
formatRange2.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
//-------for giving broder to table data
Excel.Range formatRange;
formatRange = ws.get_Range(upperLeftCell, lowerRightCell);//----------------------------------upperLeftCell, lowerRightCell
formatRange.BorderAround(Excel.XlLineStyle.xlContinuous,
Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic,
Excel.XlColorIndex.xlColorIndexAutomatic);
formatRange.HorizontalAlignment = 3;
formatRange.VerticalAlignment = 3;
//--------for giving name to the table
int lcell = cell - 3;
int rcell = cell - 2;
string tleftrange = "B" + lcell;
string trightrange = "D" + rcell;
Excel.Range chartRange1;
ws.get_Range(tleftrange, trightrange).Merge(false);//----------------------------------upperleft_cell, lowerright_cell
formatRange2 = ws.get_Range(tleftrange, trightrange);
formatRange2.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
chartRange1 = ws.get_Range(tleftrange, trightrange);
chartRange1.FormulaR1C1 = table_name;//"Ratio table";//----------------------------------table_name
chartRange1.HorizontalAlignment = 3;
chartRange1.VerticalAlignment = 3;
chartRange1.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
chartRange1.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.PaleVioletRed);
chartRange1.Font.Size = 20;
//--------drawing chart with range
Excel.Range chartRange = ws.get_Range(upperLeftCell, lowerRightCell);
xlChart.SetSourceData(chartRange, System.Reflection.Missing.Value);
xlChart.ChartType = Excel.XlChartType.xl3DPie;
// *******************Customize axes: ***********************
Excel.Axis xAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory,
Excel.XlAxisGroup.xlPrimary);
//xAxis.HasTitle = true;
// xAxis.AxisTitle.Text = "X Axis";
Excel.Axis yAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlSeriesAxis,
Excel.XlAxisGroup.xlPrimary);
//yAxis.HasTitle = true;
//yAxis.AxisTitle.Text = "Y Axis";
Excel.Axis zAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlPrimary);
//zAxis.HasTitle = true;
//zAxis.AxisTitle.Text = "Z Axis";
// *********************Add title: *******************************
xlChart.HasTitle = true;
xlChart.ChartTitle.Text = chart_name;// "Ratio";
// *****************Set legend:***************************
xlChart.HasLegend = true;
}