I found some code which uses Style property of Microsoft.Office.Interop.Excel.Worksheet.Cells[x,y] but it is treated as an object in my Visual Studo code editor:
Workbook wb = new Application.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = wb.Sheets[1];
ws.Cells[x,y] is simply treated as an object so how can I use its Style property?
I'm using Microsoft Excel 15.0 Objects Library (goes with Microsoft Office 2013). Does that matter?
Could you please explain this to me? Thank you.
you have to cast the object as a Range.
The Range interface/object contains all the style and value information for the cell or range that you are specifying.
some examples:
((Excel.Range)ws.Cells[r, c]).NumberFormat = format;
((Excel.Range)ws.Cells[r, c]).Value2 = cellVal;
((Excel.Range)ws.Cells[r, c]).Interior.Color = ColorTranslator.ToOle(Color.Red);
((Excel.Range)ws.Cells[r, c]).Style.Name = "Normal"
etc etc and so on.
Have a link:
https://learn.microsoft.com/en-us/office/vba/api/Excel.Range.Style
You might also like to check out stackoverflow.com/questions/15366340/ which includes cell formatting while exporting to excel.
Related
How to make columns to be auto width when texts in columns are long?
I use this code
Worksheet.Column(colIndex).AutoFitColumn() 'on all columns'
Worksheet.cells.AutoFitColumns()
Worksheet.Column(colIndex).BestFit = True 'on all columns'
None of these methods are working
Are there any ways to make it work?
Note: Some of my texts use Unicode.
Use AutoFitColumns, but you have to specify the cells, i assume the entire worksheet:
VB.NET
Worksheet.Cells(Worksheet.Dimension.Address).AutoFitColumns()
C#
Worksheet.Cells[Worksheet.Dimension.Address].AutoFitColumns();
Please note you need to call this method after filling the worksheet.
I have used this code with the version 3.1.3.0 of EPPlus and it is working:
worksheet.Column(1).AutoFit();
where a worksheet is the variable referencing the worksheet I have created in my code (not a class with a static method!).
Obviously you have to call this method after you have filled the columns.
Just wanted to point out you can fit cells with out specifying the range, just make sure to call this after you've formatted all columns etc:
worksheet.Cells.AutoFitColumns()
I know this is an old question, but I use the code below and it seems to directly address what you have tried to do.
using (var xls = new ExcelPackage())
{
var ws = xls.Workbook.Worksheets.Add("Some Name");
//**Add Column Names to worksheet!**
//**Add data to worksheet!**
const double minWidth = 0.00;
const double maxWidth = 50.00;
ws.Cells.AutoFitColumns(minWidth, maxWidth);
return pkg.GetAsByteArray();
}
I know is a little bit late but I've had the same problem today. If you have a worksheet.DefaultColWidthdefined, it won't work. I've removed that line and added Worksheet.cells.AutoFitColumns(); and it works now.
It's working just fine for me.
Try:
ExcelWorksheet wsSheet1 = ExcelPkg.Workbook.Worksheets.Add("Sheet1");
wsSheet1.Cells[wsSheet1.Dimension.Address].AutoFitColumns();
ExcelPkg.SaveAs();
The .NET Core as a successor of .NET doesn't support anymore the function autofit cells with EPPplus library.
worksheet.Cells.AutoFitColumns();
or
worksheet.Column(1).AutoFit();
causes exception:
"System.Drawing is not supported on this platform."
The System.Drawing assembly is dependent on GDI and Windows specific libraries which have to be replaced by another solution. The solution for this issue is to me unknown.
Had to use worksheet.Column(1).AutoFit(0); AutoFit() wasn't doing the trick.
You will need to calculate the width. There is no autosizing function in the library that will work as you intend.
Autofitcolumn will not work with wrapped text and cells with formulas.
Look at http://epplus.codeplex.com/discussions/218294?ProjectName=epplus for examples of how you can solve the problem.
I use this and is working well.
Dim objExcel As New ExcelPackage
Dim Sheet As ExcelWorksheet = objExcel.Workbook.Worksheets.Add("SheetName")
Sheet.Cells("B1:BN").AutoFitColumns()
I want to change the Xvalues in excel chart using Interop.
Following is what I am using. But it is not recognising Range.
Can anybody help me solve this?
chartPage.SetSourceData Range("A2:A4"), xlColumns
chartPage.SeriesCollection(1).XValues = Range("B2:B4")
It is not accepting Range, everywhere I am finding same answer.
Try to get the active worksheet and use range on it. Something like this:
_Worksheet ws = this.ActiveSheet
chartPage.SeriesCollection(1).XValues = ws.Range("B2:B4")
Im generating an Excel 2010 report based on a template in code using Microsoft.Office.Interop.Excel;
I need to grab the formatting from a cell in the template and apply it on subsequent cells down the column. To simplify, I want my cells to be right justified. Maybe its faster to specify this explicitly in code but I would prefer if I could base formatting on the template and not hardcode a particular style.
I am using workSheet.get_Range("L2", Type.Missing).get_Resize(1, 1) to select the cell.
Any suggestion greatly appreciated.
I'm not sure where get_Range() comes into the picture. I usually just get a Range directly.
I think what you are after is something to this effect (filler code there so you can see the variable names):
Dim oExcel As Object
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim AlignType As Long
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open("MySheet.xlsx")
oSheet = oBook.Worksheets(1)
AlignType = oSheet.Range("G1").HorizontalAlignment
oSheet.Range("G1:G" & oSheet.Range("G1").End(Excel.XlDirection.xlDown).Row).HorizontalAlignment = AlignType
Change the ranges to suit your own code.
Basically, read the value out (it's an enum, so you don't need to get the actual setting, just its number), and write it back into the other cells. You could probably do it all in one step, I separated it for clarity.
How can I get hold of the displayed format of a cell in excel interop 2007. I have a cell where the font's boldness is depending on the value in another cell. No matter if the condition is met or not, the cell.Font.Bold and cell.Style.Font.Bold properties are always false. (cell is of type Range). So is there a way to query the cell's style as the user would see it in Excel?
workbook = application.Workbooks.Open(fileName);
var worksheet = (Worksheet)workbook.Worksheets["Test"];
var cell = (Range)worksheet.Cells[8, 3];
var style = (Style)cell.Style;
strb.AppendLine("Bold: " + cell.Font.Bold); // -> False
strb.AppendLine("Bold: " + style.Font.Bold);// -> False
I also tried using the FormatConditions, but there I haven't found a way to know whether the conditions are met.
Cheers
Wullie
Unfortunately Excel doesn't give you functions 'out of the box' to tell you which conditions have been met. The best code I've seen that will tell you which conditions are active is Chuck Pearson's ActiveCondition code. You'll have to translate it from VBA to C#.
I'm using late binding to launch Excel from C# and copy data into it (Type.GetTypeFromProgID("Excel.Application"), Activator.CreateInstance, InvokeMember, and all that). I have this working fine, but I can't figure out how to set the cell format, specifically to make a cell bold. anyone have any idea how to do this?
I'm not sure how to do it late binding, but if you created an Excel helper class, this is probably the easiest way do what you want (I also added in color and number formating):
using System;
using Excel = Microsoft.Office.Interop.Excel;
public class MyClass
{
public void FormatRange(Excel.Worksheet sheet)
{
Excel.Range range = sheet.Cells["1","A"];
range.Interior.ColorIndex = 15;//This sets it to gray
range.Font.Bold = true;//Sets the Bold
range.NumberFormat = "#";//Sets it to numeric
}
}
Cheers!
SpreadsheetGear for .NET will let you read, modify and write Excel workbooks without relying on Excel being installed. If you are calling very many APIs, it will also run much faster than using Excel via COM Interop. Here is an example which loads a workbook, sets a cell's font to bold and saves the workbook:
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(#"C:\tmp\MyWorkbook.xlsx");
workbook.Worksheets["Sheet1"].Cells["A1"].Font.Bold = true;
workbook.Save();
You can see a number of live samples here and download the free trial here.
Disclaimer: I own SpreadsheetGear LLC