Auto column width in EPPlus - c#

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()

Related

Excel - How to select multiple columns as a range

I hoped and guessed we could probably have something like this:
ws.Range("D").VerticalAlignment
Which appeared to be wrong a bit later.
Edit:
previously in question I mentioned:
ws.Range("A:F").VerticalAlignment
And given a feedback which mentioned that was correct.
As you might see, I'm going to select the whole columns of A to F, what could be the right way doing so?
Hi this confused me a bit when I needed to do it as well. I'll do my best to explain!
You can select single cells (still classed as a Range I believe) using
WorkSheet.Cells[row, column]
To select multiple Cells you could do something like this
Range startCell = excelSheet.Cells[1,1];
Range endCell = excelSheet.Cells[3,3];
Range myCellCollection = excelSheet.Range[startCell, endCell];
Hope that helps a bit!
Let me know if you want any more clarification, it may not be the most efficient way but it is still running in my application :)
As you have done is fine, but you haven't passed an argument to VerticalAlignment, assuming ws is set correctly too.
Range("D:D").VerticalAlignment = xlVAlignCenter
Range("A:F").VerticalAlignment = xlVAlignTop
As a few examples.
How about selecting A1:F1 then use
activecell.EntireColumn.select();

Filter Range by specific Color Index/RGB using Worksheet.Range.Autofilter(Field,Criteria,Operator)

I am doing some automated excel manipulation using C#. I have been having a hard time figuring out how to autofilter based on a specific color.
There is very little documentation about this type of manipulation, however I have found some VB.net and VBA code for it. I cannot seem to convert the code to C# as "RGB" is not usable as it is in VB.net and VBA (See VB.net code below).
Since there has been no answers to this questions, I want to specify the code that needs to be looked at. In Autofilter(Field,Criteria,Operator), I need to know the C# Microsoft.Office.Interop.Excel criteria that would let me choose a color to filter.
Here is what my code looks like:
Excel.Worksheet xs1:
Excel.Range xRange1;
Excel.Range xRange2;
Excel.Range lastrow;
Excel.Range lastcol;
lastrow = xs1.Rows.End[Excel.XlDirection.xlDown];
lastcol = xs1.Columns.End[Excel.XlDirection.xlToRight];
xRange1 = xs1.Cells[2, 14];
xRange2 = xs1.Cells[lastrow.Row, 14];
Below selects the entire sheet and adds an autofilter(), setting it to filter for color. This works fine, but how do I pick the color I want it to filter for?
xs1.Range["A1", xs1.Cells[lastrow.Row, lastcol.Column]].
AutoFilter(14,Excel.XlColorIndex.xlColorIndexAutomatic,
Excel.XlAutoFilterOperator.xlFilterCellColor);
Here is an example of what the autofilter code would look like in VB.net. It looks very similar to this in an excel macro as well.
xs1.Range("A1", xs1.Cells(lastrow.Row, lastcol.Column)).
AutoFilter(Field:=14,Criteria1:=RGB(0,202,255),
Operator:=Excel.XlAutoFilterOperator.xlFilterCellColors)
So this is how you pick the color index for any poor souls that need to figure it out themselves. I could not find this anywhere on the internet.
xs1.Range["A1", xs1.Cells[lastrow.Row, lastcol.Column]].
AutoFilter(14, xlBook.Colors[33], Excel.XlAutoFilterOperator.xlFilterCellColor);
The important part is the "xlBook.Colors[33]". xlBook being the Workbook. 33 being the color index.
I don't have any reputation points, so I must submit an answer instead of a comment. Anyway, thank you, thank you, thank you. I have spent weeks looking for this answer and happened to search the right key words to find this post. I signed up just to upvote the answer!
My scenario is not exactly like yours, but similar enough that you led me to the solution. So, I will share what worked for me. I am trying to filter by color index using PowerShell. However, PowerShell does not allow the RGB values, as in the VB.net example above. Now, for my contribution to the answer. If you are doing this in PowerShell then it will need to look like this:
$xlFilterCellColor = 8
$xl = New-Object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open("\\path\to\file.xlsx")
$ws = $wb.worksheets.items(1)
$xlCellTypeLastCell = 11
$used = $ws.usedRange
$lastCell = $used.SpecialCells($xlCellTypeLastCell)
$range = $ws.range(A1:$lastCell)
$range.select | out-null
$range.autofilter(1,$wb.colors(6),$xlFilterCellColor)
The operator decimal values are listed here. In the code above, I am filtering yellow colored cells. Cell index colors and values can be found here.

Microsoft.Office.Interop.Excel.Worksheet.Cells[x,y].Style?

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.

NPOI create cell containing bold and non bold text

I'm using NPOI to output excel from Asp.Net MVC app and works very well with plain text but have now been requested to add formatting and am having problems where I need to have a single cell with bold text followed by non-bold text. e.g.
This text bold - this text normal
I know I can give a cell a single style but this won't help and I cannot see anyway to give a cell some pre-formatted rich text.
The only possible solution that I can think of is creating two cells separately and the merge them together but will that then mean the formatting will be lost?
Is there a way to do this that I have missed in NPOI?
You may try this:
var font = reportWorkbook.CreateFont();
font.FontHeightInPoints = 11;
font.FontName = "Calibri";
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
var cell = headerRow.CreateCell(0);
cell.SetCellValue("Test Bold");
cell.CellStyle = reportWorkbook.CreateCellStyle();
cell.CellStyle.SetFont(font);
Fortunately, you able to do that... Look at this code:
Font f1=wb.CreateFont();
f1.Color=HSSFColor.RED.index;
ws.GetRow(1).GetCell(0).RichStringCellValue.ApplyFont(1, 5, f1);
Seems that the Ernie Banzon answer no longer works exactly as described, possibly due to a namespace change (or in fact that I'm using the HSSF namespace?)
// usings
using NPOI.HSSF.UserModel;
// IWorkbook doc
IFont font = doc.CreateFont();
font.FontHeightInPoints = 11;
font.FontName = "Arial";
font.Boldweight = (short)FontBoldWeight.BOLD;
Use this option
font.Boldweight = (short)700;//FontBoldWeight.Bold;
Actual syntax should be like below. But both of these syntax doesn't works sometime
font.Boldweight = FontBoldWeight.Bold ;
Or
font.Boldweight = (short)FontBoldWeight.Bold;
FontBoldWeight is type enum, which after type casting may not work sometime. As a workaround if you type caste or use actual short value of enum directly, it works. Below is the declaration of FontBoldWeight. it will make things clear.
**public enum FontBoldWeight
{
None = 0,
Normal = 400,
Bold = 700,
}**
After a fair amount of investigation it seems that you are not able to do this inside of NPOI as it doesn't provide the necessary functionality to allow you to set formatting on specific text within a cell like I was attempting to do.

setting Excel cell format from C# using late binding

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

Categories

Resources