I am currently working in a C# application which has a class which will generate an excel file. Everything went smooth. The data populated on the excel sheet has 'Times New Roman' has font. I would like to change it to some other fonts (Calibari). How can I do that programmatically.
From what I tried, simply changing font name, size etc... on range changes font for that range:
range.Font.Name = "Arial"
range.Font.Size = 10
range.Font.Bold = true
Here is how:
//Declare Excel Interop variables
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
//Initialize variables
xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//Set global attributes
xlApp.StandardFont = "Arial Narrow";
xlApp.StandardFontSize = 10;
Focus on the 2nd line from the bottom. That sets the default font type, but I wanted to show you where xlApp came from, even if it's self explanatory.
the following worked for me, when I tried setting the default application font it did nothing so I was able to set the font name of the active sheet rows and it worked. Also worth noting I used and tested this using Excel Interop version 12
Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//Create\Add workbook object
Excel.Workbooks workBooks = excelApp.Workbooks;
//Excel.Workbook
Excel.Workbook workBook = workBooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
//use worksheet object
Excel.Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
//set default font
workSheet.Rows.Font.Name = "Arial";
Have you tried something like this:
new Font("Arial", 10, FontStyle.Bold);
var range = worksheet.get_Range(string.Format("{0}:{0}", startRowIndex, Type.Missing));
range = range.EntireRow;
range.Style.Font.Name = "Arial";
range.Style.Font.Bold = false;
range.Style.Font.Size = 12;
Hey Do not upset I do it and works for me .
Just define Font.Name and excell sheet fill all sheet use everywhere .
Any Way Code is :
workSheet.Range[workSheet.Cells[1, tempCount], workSheet.Cells[1, tempCount + mergeCount-1]].Merge();
workSheet.Range[workSheet.Cells[1, tempCount], workSheet.Cells[1, tempCount + mergeCount - 1]].Interior.Color = ColorTranslator.ToOle(Color.FromArgb(23,65,59));
workSheet.Range[workSheet.Cells[1, tempCount], workSheet.Cells[1, tempCount + mergeCount - 1]].Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
workSheet.Range[workSheet.Cells[1, tempCount], workSheet.Cells[1, tempCount + mergeCount - 1]].Style.Font.Name = "Arial Narrow";
((Excel.Range)WorksheetResult.UsedRange).Font.Name = "Avant Garde";
WorksheetResult is just a sheet reference.
Found this thread by my own similar problem. I had a little picker box that, when a cell was clicked, needed to paste a unique font's symbol into the selected excel cell. Here's how i did that:
string selectedItem = arrayOfSymbols[tableLayoutPanel1.GetRow((Control)sender), tableLayoutPanel1.GetColumn((Control)sender)];
Excel.Worksheet ws = Globals.ThisAddIn.Application.ActiveSheet;
Excel.Range cell = Globals.ThisAddIn.Application.ActiveCell;
ws.Cells[cell.Row, cell.Column].Font.Name = "My Custom Font";
ws.Cells[cell.Row, cell.Column] = selectedItem;
Related
I have an application in which I'm trying to write to an Excel file. It doesn't seem to be working.
Here is my code:
using System;
using System.Drawing;
using Microsoft.Office.Interop.Excel;
namespace Image2Excel {
class Engine {
public static void go(string imageFilename, string excelFilename = null) {
//Image img = Image.FromFile(imageFilename);
Bitmap btm = (Bitmap)Bitmap.FromFile(imageFilename, false);
Image img = Image.FromFile(imageFilename, false);
if (btm != null) {
Color[][] colorArray = new Color[btm.Width][];
for (int x = 0; x < btm.Width; x++) {
colorArray[x] = new Color[btm.Height];
for (int y = 0; y < btm.Height; y++) {
colorArray[x][y] = btm.GetPixel(x, y);
}
}
var excel = new Microsoft.Office.Interop.Excel.Application();
var workbook = excel.Workbooks.Add(Type.Missing);
var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
worksheet.Name = "sheet1";
worksheet.Cells[1,1] = "top left";
worksheet.Cells[1,2] = "top right";
worksheet.Cells[2,1] = "bottom left";
worksheet.Cells[2,2] = "bottom right";
workbook.SaveAs("temp.xlsx");
workbook.Close();
excel.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(excel);
}
}
}
}
I'm trying to write some text to the first 4 cells in the spreadsheet. It's not working. When I open the file, I see nothing in the cells.
I do see that the sheet name is set to what I set it to so I know it's writing to the files.
One thing I noticed when I debug is that worksheet.Cells[1,1] is null after I set it. I'm wondering if I need to set the cell to an object before writing to it. But I'm not sure how. I don't seem to be able to do this:
worksheet.Cells[1,1] = new Microsoft.Office.Interop.Excel.Cell();
Hovering over Cells tells me it's a Range object, but I'm not sure how to set it to a range either. I tried this:
worksheet.Range["A1"].Value = "hello";
worksheet.Range["A1"].Value2 = "hello";
...but those don't work either. worksheet.Range remains null just like worksheet.Cells.
How can I make sure worksheet.Cells[1,1] or worksheet.Range["A1"] is set to an object that will take a string value? Thanks.
You can find my application on github: https://github.com/gibran-shah/Image2Excel
I'm using Microsoft.Office.Interop.Excel version 15.0.4795.1000.
I have Excel 2010 installed on my computer.
I haven't tried yours but could you try these methods? it worked for me.
1st method with Worksheets.Cells
// CREATE EXCEL OBJECTS.
Excel.Application xlApp;
Excel.Workbook xlWB;
Excel.Worksheet xlWS;
xlApp = new Excel.Application();
// Specify the path to the excel file
xlWB= xlApp.Workbooks.Open("path/to/xlFile.xls");
// Choose the sheet you want to open
xlWS = xlWB.Worksheets["Sheet1"];
// Write on the single cell
xlWS.Cells["1", "D"] = "Example";
// Save the change and quit
xlWB.Close(true);
xlApp.Quit();
2nd method with Worksheets.get_Range()
// CREATE EXCEL OBJECTS.
Excel.Application xlApp;
Excel.Workbook xlWB;
Excel.Worksheet xlWS;
xlApp = new Excel.Application();
// Specify the path to the excel file
xlWB= xlApp.Workbooks.Open("path/to/xlFile.xls");
// Choose the sheet you want to open
xlWS = xlWB.Worksheets["Sheet1"];
// Write on the range of cells
xlWS.get_Range["A3", "D5"] = "Example";
// Save the change and quit
xlWB.Close(true);
xlApp.Quit();
In my application I have a requirement to create an excel file contains several combos.I have created upto that.
Now I have to read those combo's value from excel.
I have found a link to read from excel Read From Excel
But In my code I have found this..
Here is my code
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Open("C:\\TopicUpload_2017October14.xls"));
//3rd Sheet
oSheet = (Microsoft.Office.Interop.Excel._Worksheet) oWB.Sheets.get_Item(1);
Microsoft.Office.Interop.Excel.DropDowns allDropDowns = oSheet.DropDowns(Type.Missing);
Microsoft.Office.Interop.Excel.DropDown oneDropdown = allDropDowns.Item("2");
Now how can I get selected text of this dropdown.. When I inspect I got
oneDropdown.ListCount = 5.0; // items count of second drop down, which is true
But could not able to get selected text.
oneDropdown.Text
After searching , I'm able to get it.
#region Read value from excel combobox
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Open("C:\\TopicUpload_2017October14.xls"));
//3rd Sheet
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.Sheets.get_Item(1);
Microsoft.Office.Interop.Excel.DropDowns allDropDowns = oSheet.DropDowns(Type.Missing);
Microsoft.Office.Interop.Excel.DropDown oneDropdown = allDropDowns.Item("1"); // first combo
string selectedText = oneDropdown.get_List(oneDropdown.ListIndex);
#endregion
I am writing a C# program which copies a range of cells from a worksheet of one workbook to a worksheet of an other workbook. But the problem I am facing is I am only able to copy and paste the whole worksheet of first workbook. I want to know how to select only a specific range(from row 5 [column 1 to column 10] to row 100 [column 1 to column 10]) and paste it in second workbook worksheet starting from row 2 column 8.
Also i want to know how a fill a column say from C1 to C100 with some value in a direct way instead of using the loop like below
for(i=1;i<2;i++)
{
for(j=1;j<101;i++)
{
worksheet.cells[i,j]="Fixed";
}
}
Here is the code that i have written so far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Excel.Application srcxlApp;
Excel.Workbook srcworkBook;
Excel.Worksheet srcworkSheet;
Excel.Range srcrange;
Excel.Application destxlApp;
Excel.Workbook destworkBook;
Excel.Worksheet destworkSheet;
Excel.Range destrange;
string srcPath;
string destPath;
//Opening of first worksheet and copying
srcPath="C:\\Documents and Settings\\HARRY\\Desktop\\incident.csv";
srcxlApp = new Excel.Application();
srcworkBook = srcxlApp.Workbooks.Open(srcPath);
srcworkSheet = srcworkBook.Worksheets.get_Item(1);
srcrange = srcworkSheet.UsedRange;
srcrange.Copy(Type.Missing);
//opening of the second worksheet and pasting
destPath = "C:\\Documents and Settings\\HARRY\\Desktop\\FIXED Aging incident Report.xls";
destxlApp = new Excel.Application();
destworkBook = destxlApp.Workbooks.Open(destPath,0,false);
destworkSheet = destworkBook.Worksheets.get_Item(1);
destrange = destworkSheet.Cells[1, 1];
destrange.Select();
destworkSheet.Paste(Type.Missing, Type.Missing);
destworkBook.SaveAs("C:\\Documents and Settings\\HARRY\\Desktop\\FIXED Aging incident Report " + DateTime.Now.ToString("MM_dd_yyyy") + ".xls");
srcxlApp.Application.DisplayAlerts = false;
destxlApp.Application.DisplayAlerts = false;
destworkBook.Close(true, null, null);
destxlApp.Quit();
srcworkBook.Close(false, null, null);
srcxlApp.Quit();
}
}
}
You should be able to do this:
Excel.Range from = srcworkSheet.Range("C1:C100");
Excel.Range to = destworkSheet.Range("C1:C100");
from.Copy(to);
mrtig has a very elegant solution. But it won't work if you have the workbooks in separate instances of excel. So, the key is to open them in just one instance. I've modified your example to show using this approach:
public void CopyRanges()
{
// only one instance of excel
Excel.Application excelApplication = new Excel.Application();
srcPath="C:\\Documents and Settings\\HARRY\\Desktop\\incident.csv";
Excel.Workbook srcworkBook = excelApplication.Workbooks.Open(srcPath);
Excel.Worksheet srcworkSheet = srcworkBook.Worksheets.get_Item(1);
destPath = "C:\\Documents and Settings\\HARRY\\Desktop\\FIXED Aging incident Report.xls";
Excel.Workbook destworkBook = excelApplication.Workbooks.Open(destPath,0,false);
Excel.Worksheet destworkSheet = destworkBook.Worksheets.get_Item(1);
Excel.Range from = srcworkSheet.Range("C1:C100");
Excel.Range to = destworkSheet.Range("C1:C100");
// if you use 2 instances of excel, this will not work
from.Copy(to);
destworkBook.SaveAs("C:\\Documents and Settings\\HARRY\\Desktop\\FIXED Aging incident Report " + DateTime.Now.ToString("MM_dd_yyyy") + ".xls");
srcxlApp.Application.DisplayAlerts = false;
destxlApp.Application.DisplayAlerts = false;
destworkBook.Close(true, null, null);
srcworkBook.Close(false, null, null);
excelApplication.Quit();
}
For the First part of setting the same value for the entire range, instead of looping following will work out
range1 = workSheet.get_Range("A1:B100");
range1.Value = "Fixed";
And for copying you can try what #mrtig has suggested.
I have created the sheet1 and populated some data in the sheet, using the data from sheet1 i want to create a chart sheet with ploting the data
try
{
app = new Excel.Application();
app.Visible = true;
workbook = app.Workbooks.Add(1);
worksheet = (Excel.Worksheet)workbook.Sheets[1];
PopulateDateInExcel(pathtologsfolder, startdate, enddate);
// create a chart
Excel.Range chartRange;
object misValue = System.Reflection.Missing.Value;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)worksheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)workbook.Charts[2];
Excel.Chart chartPage = myChart.Chart;
chartRange = worksheet.get_Range("AN1", "AP6");
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Excel.XlChartType.xl3DLine;
}
catch (Exception e)
{
//Console.Write("Error");
}
finally
{
}
Thanks in advance,
Excel Automation
Try this (UNTESTED)
Excel.ChartObject myChart = (Excel.ChartObject)charts.Add(10, 70, 250, 250);
instead of
Excel.ChartObject myChart = (Excel.ChartObject)workbook.Charts[2];
and then once your chart is created, move it to a chart sheet using this code
chart.Location(XlChartLocation.xlLocationAsNewSheet, Type.Missing);
The way to do this would be to use the Add method:
Excel.Workbook xlWorkbook;
Excel.Chart chartName = (Excel.Chart)xlWorkbook.Charts.Add();
Admittedly, at least in my experiments this causes trouble as the dataset it is using by default is fairly random (Excel magic...) so you might be needing to reformat it afterwards (delete and add datasets, etc), but that's the method to do it.
EDIT:
I should note that Excel support documentation seems to recommend the Add2 method method, but I haven't managed to use it successfully:
Excel.Workbook xlWorkbook;
Excel.Chart chartName = (Excel.Chart)xlWorkbook.Charts.Add2();
Excel.Application oXL = new Excel.Application();
and after then
oXL.Run() and see attached:
I'm using C# COM Interop to create and update Excel files on the fly. I used the below code. But I'm not sure how to add color to a particular cell. Please help me with the same.
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook wb = excel.Workbooks.Open(excel_filename);
Excel.Worksheet sh = wb.Sheets.Add();
sh.Name = "TestSheet";
sh.Cells[1, "A"].Value2 = "SNO";
sh.Cells[2, "B"].Value2 = "A";
sh.Cells[2, "C"].Value2 = "1122";
wb.Close(true);
excel.Quit();
Try this
wb.Cells[row, clmn].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)